简体   繁体   English

用Python编写后文件开头的奇怪字符

[英]Strange characters in the begining of the file after writing in Python

I want to do a lot of boring C# code replacements automatically through a python script. 我想通过python脚本自动进行很多无聊的C#代码替换。 I read all lines of the file, transform them, truncate the whole file, write new strings and close it. 我读取了文件的所有行,对其进行了转换,截断了整个文件,编写了新字符串并关闭了它。

f = open(file, 'r+')
text = f.readlines()
# some changes
f.truncate(0)
for line in text:
    f.write(line)
f.close()

All my changes are written. 我的所有更改均已写入。 But some strange characters in the beginning of the file appear. 但是文件开头会出现一些奇怪的字符。 I don't know how to avoid them. 我不知道如何避免它们。 Even if I open with encoding='utf-8-sig' it doesn't help. 即使我使用encoding='utf-8-sig'打开,它也无济于事。

I tried truncate whole file besides the 1st line like this: 我尝试截断除了第一行之外的整个文件,如下所示:

import sys
f.truncate(sys.getsizeof(text[0]))
for index in range(1, len(text), 1):
    f.write(text[index])

But in this case more than 1st line is writing instead of only first line. 但是在这种情况下,要写的不仅仅是第一行,而不仅仅是第一行。

EDIT I tried this: 编辑我尝试了这个:

f.truncate(len(text[0]))
for index in range(1, len(text), 1):
    f.write(text[index])

And the first line has written correct but next one with the same issue. 第一行写的正确,但下一行写的相同。 So I think this characters from the end of the file and I try to write after them. 因此,我认为这些字符来自文件末尾,我尝试在它们之后编写。

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()

Check out this Link for more details. 查看此链接以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM