[英]Appending characters to each line in a txt file with python
我編寫了以下python代碼段,將小寫p字符附加到txt文件的每一行:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
但是,當我執行此python程序時,它只返回一個空空白:
zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
誰能告訴我我的密碼有什么問題嗎?
當前,您只讀取每一行,而不寫入文件。 在寫入模式下重新打開文件並向其中寫入完整的字符串,如下所示:
newf=""
with open('helloworld.txt','r') as f:
for line in f:
newf+=line.strip()+"p\n"
f.close()
with open('helloworld.txt','w') as f:
f.write(newf)
f.close()
open(filePath, openMode)
有兩個參數,第一個是文件的路徑,第二個是將其打開的模式。 當使用'r'
作為第二個參數時,實際上是在告訴Python將其作為唯一讀取文件打開。
如果要在其上進行寫操作,則需要以寫模式打開它,並使用'w'
作為第二個參數。 您可以在其官方文檔中找到有關如何在Python中讀取/寫入文件的更多信息。
如果要同時讀取和寫入,則必須以讀取和寫入兩種方式打開文件。 您只需使用'r+'
模式即可完成此操作。
好了,在shell中鍵入help(f),您可以獲得“ BufferedIOBase對象緩沖區上基於字符和行的圖層”。 意思是:如果您讀第一個緩沖區,您可以得到內容,但是再次獲得。 它是空的。所以像這樣:
with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
newline = ''
for line in f1:
newline+=line.strip()+"p\n"
f2.write(newline)
似乎您的for循環已經讀取f.read()
文件,因此f.read()
返回空字符串。
如果只需要打印文件中的行,則可以像print(line)
一樣將打印內容移動到for循環中。 並且最好將f.read()移至for循環之前:
f = open("filename", "r")
lines = f.readlines()
for line in lines:
line += "p"
print(line)
f.close()
如果需要修改文件,則需要創建另一個文件obj並以“ w”模式打開它,然后使用f.write(line)
將修改后的行寫入新文件。
此外,最好在python中使用with子句,而不要使用open(),它更像pythonic。
with open("filename", "r") as f:
lines = f.readlines()
for line in lines:
line += "p"
print(line)
使用with子句時,您無需關閉文件,這更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.