写入 Python 后文件开头出现奇怪字符
Strange characters in the begining of the file after writing in Python
我想通过 python 脚本自动替换很多无聊的 C# 代码。我读取文件的所有行,转换它们,截断整个文件,写入新字符串并关闭它。
f = open(file, 'r+')
text = f.readlines()
# some changes
f.truncate(0)
for line in text:
f.write(line)
f.close()
我的修改都写好了。但是文件开头出现了一些奇怪的字符。我不知道如何避免它们。即使我用 encoding='utf-8-sig'
打开也无济于事。
我试过像这样截断除第一行之外的整个文件:
import sys
f.truncate(sys.getsizeof(text[0]))
for index in range(1, len(text), 1):
f.write(text[index])
但在这种情况下,不止第一行正在写入,而不仅仅是第一行。
编辑
我试过这个:
f.truncate(len(text[0]))
for index in range(1, len(text), 1):
f.write(text[index])
而且第一行写对了,但下一行写的是同样的问题。所以我认为这个字符来自文件末尾,我尝试在它们之后写。
f=open(file, 'r+')
text = f.readlines() # After reading all the lines, the pointer is at the end of the file.
# some changes
f.seek(0) # To bring the pointer back to the starting of the file.
f.truncate() # Don't pass any value in truncate() as it means number of bytes to be truncated by default size of file.
for line in text:
f.write(line)
f.close()
查看此 Link 了解更多详情。
我想通过 python 脚本自动替换很多无聊的 C# 代码。我读取文件的所有行,转换它们,截断整个文件,写入新字符串并关闭它。
f = open(file, 'r+')
text = f.readlines()
# some changes
f.truncate(0)
for line in text:
f.write(line)
f.close()
我的修改都写好了。但是文件开头出现了一些奇怪的字符。我不知道如何避免它们。即使我用 encoding='utf-8-sig'
打开也无济于事。
我试过像这样截断除第一行之外的整个文件:
import sys
f.truncate(sys.getsizeof(text[0]))
for index in range(1, len(text), 1):
f.write(text[index])
但在这种情况下,不止第一行正在写入,而不仅仅是第一行。
编辑 我试过这个:
f.truncate(len(text[0]))
for index in range(1, len(text), 1):
f.write(text[index])
而且第一行写对了,但下一行写的是同样的问题。所以我认为这个字符来自文件末尾,我尝试在它们之后写。
f=open(file, 'r+')
text = f.readlines() # After reading all the lines, the pointer is at the end of the file.
# some changes
f.seek(0) # To bring the pointer back to the starting of the file.
f.truncate() # Don't pass any value in truncate() as it means number of bytes to be truncated by default size of file.
for line in text:
f.write(line)
f.close()
查看此 Link 了解更多详情。