[英]Replacing line in text file with python. How to?
我在這里和那里一直在尋找如何用新行替換文件中的多行,但是我的代碼只是在文件的末尾添加了一行。 如何在適當的地方用新的線代替舊的線?
path = /path/to/file
new_line = ''
f = open(path,'r+b')
f_content = f.readlines()
line = f_content[63]
newline = line.replace(line, new_line)
f.write(newline)
f.close()
編輯:path = / path / to / file path_new = path +“。tmp” new_line =“”,其中open(path,'r')為inf,open(path_new,'w')為outf:對於num,行枚舉(inf):如果num == 64:newline = line.replace(line,new_line)outf.write(newline)else:outf.write(line)new_file = os.rename(path_new,path)
大多數操作系統將文件視為二進制流,因此文件中沒有什么像一行。 因此,您必須重寫整個文件,並用以下行替換:
new_line = ''
with open(path,'r') as inf, open(path_new, 'w') as outf:
for num, line in enumerate(inf):
if num == 64:
outf.write(new_line)
else:
outf.write(line)
os.rename(path_new, path)
通常,您必須重寫整個文件。
操作系統將文件公開為字節序列。 當您打開文件時,此序列具有與其關聯的所謂的文件指針 。 當您打開文件時,指針位於開頭。 您可以從該位置讀取或寫入字節,但不能插入或刪除字節。 讀取或寫入n個字節后,文件指針將移位n個字節。
此外,Python還提供了一種讀取整個文件並將內容拆分為幾行列表的方法。 在這種情況下,這更方便。
# Read everything
with open('/path/to/file') as infile:
data = infile.readlines()
# Replace
try:
data[63] = 'this is the new text\n' # Do not forget the '\n'!
with open('/path/to/file', 'w') as newfile:
newfile.writelines(data)
except IndexError:
print "Oops, there is no line 63!"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.