python - 关注列表中的每个值

标签 python python-3.x list fwrite

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

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 个小更改即可修复此问题。

  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

关于python - 关注列表中的每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53357735/

相关文章:

python - 如何找到列表中项目的索引,但不是完全匹配

python - 在 python 中对列表或列表列表进行字符串化并将其转换回原始形式的问题

javascript - 将 <a> 放在 <tr> 中的更好做法是什么

c++ - 另一个 C++ 列表问题

python - 从同一网络的另一台机器访问 Django devserver

python - 不断收到 ValueError : not enough values to unpack (expected 2, 得到 1)

python - 为什么在 Python 中使用 Mergesort 时返回值为 0?

python - pd.concat() 不在同一索引上合并

python - 使用正则表达式解析字符串

python - 在 Python 中使用可变数量的 .format() 参数进行格式化