【问题标题】:Python: Replace function to edit filesPython:替换函数来编辑文件
【发布时间】:2011-05-07 04:07:34
【问题描述】:

我有一个results.txt 文件,如下所示:

[["12 - 22 - 30 - 31 - 34 - 39 - 36"],
["13 - 21 - 28 - 37 - 39 - 45 - 6"],
["2 - 22 - 32 - 33 - 37 - 45 - 11"],
["3 - 5 - 11 - 16 - 41 - 48 - 32"],
["2 - 3 - 14 - 29 - 35 - 42 12"],
["14 - 30 - 31 - 36 - 44 - 47 26"]]

我想用 '","' 替换 results.txt 文件中的“-”,这样它看起来就像一个 python 列表。

我尝试使用下面的代码,但输出看起来与 results.txt 完全一样

output = open("results2.txt", 'w')
f = open("results.txt", 'r')
read = f.readlines()

for i in read:
    i.replace(" - ",'","')
    output.write(i)

【问题讨论】:

    标签: python file replace


    【解决方案1】:
    for i in read:
        # the string.replace() function don't do the change at place
        # it's return a new string with the new changes.
        a = i.replace(" - ",",")  
        output.write(a)
    

    【讨论】:

      【解决方案2】:

      字符串方法返回一个新字符串。把它写出来。

      output.write(i.replace(" - ",","))
      

      【讨论】:

        【解决方案3】:

        i.replace(" - ",'","') 不会改变 i(记住字符串是不可变的)所以你应该使用

        i = i.replace(" - ",'","')
        

        如果文件不是很大(我猜 - 因为你是用readlines() 一次将它全部读入内存),你可以一次完成整个文件

        output = open("results2.txt", 'w')
        f = open("results.txt", 'r')
        output.write(f.read().replace(" - ".'","'))
        f.close()
        output.close()
        

        【讨论】:

          猜你喜欢
          • 2023-03-19
          • 2018-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多