使用 python 将字符附加到 txt 文件中的每一行
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 程序时,它 returns 除了一片空白什么都没有:
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'
作为第二个参数。您可以在其 official documentation.
中找到有关如何 Python 中 read/write 文件的更多信息
如果要同时读取和写入,则必须同时以读取和写入模式打开文件。您只需使用 'r+'
模式即可做到这一点。
嗯,在shell中输入help(f),你可以得到"Character and line based layer over a BufferedIOBase object, buffer."
意思是:如果你读第一个缓冲区,你可以得到内容,但是要重复。它是空的。
像这样:
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()
return空字符串。
如果你只需要打印文件中的行,你可以像print(line)
一样将打印移动到for循环中。并且最好在 for 循环之前移动 f.read():
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子句时,不需要关闭文件,这样更简单。
我编写了以下 python 代码片段以将小写的 p 字符附加到 txt 文件的每一行:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
然而,当我执行这个 python 程序时,它 returns 除了一片空白什么都没有:
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'
作为第二个参数。您可以在其 official documentation.
如果要同时读取和写入,则必须同时以读取和写入模式打开文件。您只需使用 'r+'
模式即可做到这一点。
嗯,在shell中输入help(f),你可以得到"Character and line based layer over a BufferedIOBase object, buffer." 意思是:如果你读第一个缓冲区,你可以得到内容,但是要重复。它是空的。 像这样:
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()
return空字符串。
如果你只需要打印文件中的行,你可以像print(line)
一样将打印移动到for循环中。并且最好在 for 循环之前移动 f.read():
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子句时,不需要关闭文件,这样更简单。