0
我想編輯python中的文本文件中的一行。在python中編輯文本文件中的特定行
我有一個文本文件
name:
address:
age:
我需要的東西添加到上述文件的一些具體的Fileds。基本上填滿了一些領域。
例如: 輸出應
name:
address:xxx
age:20
我想編輯python中的文本文件中的一行。在python中編輯文本文件中的特定行
我有一個文本文件
name:
address:
age:
我需要的東西添加到上述文件的一些具體的Fileds。基本上填滿了一些領域。
例如: 輸出應
name:
address:xxx
age:20
我喜歡用fileinput
模塊就位編輯文件,就像這樣:
import fileinput
import sys
for line in fileinput.input(inplace=True):
# Whatever is written to stdout or with print replaces
# the current line
if line.startswith("address:"):
print("address:xxx")
elif line.startswith("age:"):
print("age:20")
else:
sys.stdout.write(line)
簡單地傳遞文件名作爲參數傳遞給python命令,例如:
python myprogram.py data.txt
可能重複[How t o將文本添加到字符串中一行的末尾? - Python](http://stackoverflow.com/questions/8830029/how-to-add-text-to-the-end-of-a-line-in-a-string-python) –
你不能編輯一個文件就地。您必須全部閱讀,然後替換您的數據,然後將其寫回。 –
讀取所有行,修改您所需的內容,將所有行寫入文件。 – furas