Python - 反转整个文件

标签 python file reverse

我需要能够反转整个文件,或者至少是它的内容。到目前为止我的代码是:

def reverse_file(of, rf):
     oldfile = open(of, 'r')
     reversefile = open(rf, 'w')
     filedata = oldfile.read()
     rdata = str_reverse(filedata)
     reversefile.write(rdata)
     oldfile.close()
     reversefile.close()

问题是我需要定义 str_reverse 并且我不确定如何创建一个反转所有内容的函数。有帮助吗?

最佳答案

如果你想反转整个文件,你可以用data[::-1]调用write

def reverse_file(of, rf):
    with open(of) as oldfile:
        with open(rf, "w") as reversefile:
            reversefile.write(oldfile.read()[::-1])

例子:

% cat testdata
line1
line2
line3
% cat reverse_file.py
def reverse_file(of, rf):
    with open(of) as oldfile:
        with open(rf, "w") as reversefile:
            reversefile.write(oldfile.read()[::-1])

if __name__ == "__main__":
    reverse_file("testdata", "newdata")
% python reverse_file.py
% cat newdata

3enil
2enil
1enil

关于Python - 反转整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409969/

相关文章:

c - 如何在 C 中对 .txt 文件内的数据进行排序

php - 如何使用php搜索文件

linux - 通过在 linux 中删除 url 参数来重命名文件

python - 反转图例的顺序

iphone - 是否可以将 NSMutableArray 转换为 iPhone 中的相反顺序?

javascript - 我不知道如何修复我的反向数组/字符串

python - 我可以将逻辑运算符 "or"与字符串结合使用吗?

python - python中如何匹配不同写法的键名?

python - 判断 python 是否允许从 python 脚本中进行线程化

python - 从 CSV 文件中提取列以用作 NetworkX 中的节点列表