集中到列表中的每个值

Concenating to every value in a list

所以我有一个包含几行文本的文件:

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)

它出于某种原因打印空列表。

如果您在 'w' 模式下打开文件,文件将被删除。来自 docs:

'w' for only writing (an existing file with the same name will be erased)

您还应该使用 with 关键字:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes...

我建议你先读取文件的内容,处理数据,然后写入:

def reverseFile(file_name):
    with open(file_name, 'r') as f:
        file_lines = [line.rstrip('\n') for line in f.readlines()]
    file_lines.reverse()
    with open(file_name, "w") as f:
        for line in file_lines:
            f.write(line + '\n')

reverseFile('text_lines.txt') 

您只需在脚本中做 2 处小改动即可修复它。

  1. \r+代替\w+

  2. 在执行写操作之前,将文件位置指示器放在开头

    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