0
我有以下行蟒蛇寫入文本文件的選項
test1
test2
test3
一個文本文件,我想python腳本插入在文件的頂部一個新行,然後後像編輯的每一行以下
Python
Test : test1 -t
Test : test2 -t
Test : test3 -t
有什麼建議嗎?
感謝
我有以下行蟒蛇寫入文本文件的選項
test1
test2
test3
一個文本文件,我想python腳本插入在文件的頂部一個新行,然後後像編輯的每一行以下
Python
Test : test1 -t
Test : test2 -t
Test : test3 -t
有什麼建議嗎?
感謝
我就從嘗試直接操縱文件望而卻步 - 我甚至不知道這是工作。這是更簡單的讀取文件,然後覆蓋新文件 - 只要你輸入的文件將不會超過你的記憶:如果記憶是一個令人關注的
with open('file.txt') as fin:
# get lines of the file as list
lines = fin.readlines()
# Overwrite file.txt with new content
with open('file.txt','w') as fout:
fout.write('Python\n')
for line in lines:
fout.write('Test: ' + line.strip() + ' -t\n')
,你不介意得到一個新的文件:
with open('file.txt') as fin:
fout = open('newfile.txt','w')
fout.write('Python\n')
for line in fin:
fout.write('Test: ' + line.strip() + ' -t\n')
fout.close()
你可以發表你曾嘗試過嗎?嘗試查看[doc](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) – fredtantini
我不知道在代碼中插入新行頂部或如何插入每行或結尾的開頭..我只知道如何寫入文件 – abualameer94
閱讀文件,進行更改,只需寫入新文件或覆蓋舊文件。您可以使用'readlines()'來獲取文件的所有行。 – mattmilten