【问题标题】:reading a file and writing in reverse读取文件并反向写入
【发布时间】:2015-08-30 01:19:17
【问题描述】:

我正在尝试读取文件并使用反向行继续写入。到目前为止,这是我的代码:

def write_reversed_file(input_filename, output_filename):
"""Writes a reverse file"""
    with open(input_filename, 'r') as input_file:
        data = input_file.readlines()
    with open(output_filename, 'w') as output_file:
        return output_file.reversed(data)

try:
    write_reversed_file('data.txt', 'reversed.txt')
    print(open('reversed.txt').read())
except IOError:
    print ("Error: can't find file or read data"

【问题讨论】:

  • 你想从这个社区得到什么?您的问题没有任何要求。
  • 对不起,我只是想知道如何读取文件并编写它的反转版本
  • 看起来像家庭作业,其他人可能以前在 SO 上问过它:stackoverflow.com/questions/29586063/…
  • output_file.reversed(data) 无效。见the python tutorial on file objects
  • 你的意思是颠倒了行的顺序,还是颠倒了行中的字符,还是两者都颠倒了?

标签: python file


【解决方案1】:

你什么都没问!!!此外,在要求人们修复您的代码之前,您应该尝试通过自己的方式或在 StackOverflow 上找到答案。

嗯,你的下半场是错的。

 with open(output_filename, 'w') as output_file:
  for i in reversed(data):
    output_file.write(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多