所以我有一个包含一些文本行的文件:
here's a sentence
look! another one
here's a third one too
and another one
one more
我有一些代码,它获取每一行并将其放入一个列表中,然后反转整个列表的顺序,但现在我不知道如何将每一行写回文件并删除其中现有的行文本文件。
此外,当我运行此代码时:
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
一切正常,行顺序相反,但是当我运行此代码时:
text_file = open(file_name, "w")
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
for line in file_lines:
text_file.write(line)
由于某种原因它打印空列表。
最佳答案
您只需在脚本中进行 2 个小更改即可修复此问题。
使用
\r+
代替\w+
在执行写操作之前,将文件位置指示器置于开头
text_file.seek(0)
» rw_file.txt
- 操作前
here's a sentence
look! another one
here's a third one too
and another one
one more
下面是您修改后的脚本,用于反转文件内容(它有效)。
def reverseFile(file_name):
text_file = open(file_name, "r+") # Do not use 'w+', it will erase your file content
file_lines = [line.rstrip('\n') for line in text_file.readlines()]
file_lines.reverse()
print(file_lines)
text_file.seek(0) # Place file position indicator at beginning
for line_item in file_lines:
text_file.write(line_item+"\n")
reverseFile("rw_file.txt")
» rw_file.txt
- 操作后
one more
and another one
here's a third one too
look! another one
here's a sentence
关于python - 关注列表中的每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53357735/