python小端模式讀寫txt

2021-10-10 07:29:25 字數 1934 閱讀 1030

經嘗試,在windows下utf-16對應小端模式,utf-16-le不對應任何模式。

小端模式使用notapad++可以檢視生成檔案的模式,對應ucs-2 little endian編碼。

小端模式對應檔案頭 \ufeff.

# coding=utf-8

import os

import codecs

def check_charset(file_path):

import chardet

with open(file_path, "rb") as f:

data = f.read(4)

charset = chardet.detect(data)['encoding']

return charset

def readfile(path):

ofile = open(path, encoding='utf-8')

file_lineinfo = open("utf-16.txt", 'w', encoding='utf-16')

lines = ""

lines = ofile.readlines()

encoding = none

lst =

if lines[0].startswith('\ufeff'):

for line in lines:

print(line)

if line.startswith('\ufeff'):

contents = line[1:]

else:

contents = line

file_lineinfo.writelines(contents)

file_lineinfo.close()

encoding = 'utf-16-le'

ofile.close()

import codecs

ofile = codecs.open(path, 'r', encoding)

lst = ofile.readlines()

ofile.stream.close()

else:

file_lineinfo.writelines('\n')

for line in lines:

print(line)

if line.startswith('\ufeff'):

contents = line[1:]

else:

contents = line

file_lineinfo.writelines(contents)

file_lineinfo.close()

def parsefile(filepath):

try:

linelist = # 存放每一行的內容

with open(filepath, encoding=check_charset(filepath)) as fp:

line = fp.read()

print(line)

if line.startswith('\ufeff'):

encoding = 'utf-16-le'

fp2 = codecs.open(filepath, 'r', encoding)

linelist = fp2.readlines()

fp2.stream.close()

for i in linelist: # 列印每一行

print(i)

except exception as ex:

print('[error]--', ex)

if __name__ == '__main__':

filepath = './test.txt'

parsefile(filepath)

readfile(filepath)

Python 讀寫txt檔案

1 讀取 usr bin python coding utf 8 import os str r c users d1 desktop test.txt f open str,r content f.read print content f.close 2 寫入 str c users d1 des...

python檔案txt讀寫

在鍵盤隨便敲了幾個字並建立了乙個文字檔案 1.txt 我們要使用python將其進行讀寫操作 1 檔案讀寫操作 讀檔案1.txt 使用open和read f open 1.txt print f.read f.close 輸出 de鍝堝搱dfafadsfasdfasd fasdfasdfjasdkh...

Python讀寫txt檔案

最近,我在嘗試用python製作乙個簡單的桌面軟體,但其中遇見幾個小問題想給大家分享一下 一般檔案讀寫都是這樣的 讀取 f open test.txt r txt f.read f.close 寫入with open test.txt w as f f.write nothing f.close那,...