【问题标题】:how to properly read and modify a file using python如何使用python正确读取和修改文件
【发布时间】:2012-10-31 02:42:39
【问题描述】:

我正在尝试从文件中删除所有(非空格)空白字符并用逗号替换所有空格。这是我当前的代码:

def file_get_contents(filename):
  with open(filename) as f:
    return f.read()

content = file_get_contents('file.txt')
content = content.split
content = str(content).replace(' ',',')
with open ('file.txt', 'w') as f:
  f.write(content)

当它运行时,它将文件的内容替换为:

<built-in,method,split,of,str,object,at,0x100894200>

【问题讨论】:

    标签: python string text file-io


    【解决方案1】:

    您遇到的主要问题是您将方法content.split 分配给内容,而不是调用它并分配其返回值。如果您在分配后打印出content,它将是:&lt;built-in method split of str object at 0x100894200&gt;,这不是您想要的。通过添加括号来修复它,使其成为方法的调用,而不仅仅是对它的引用:

    content = content.split()
    

    我认为您在解决该问题后可能仍然存在问题。 str.split 返回一个列表,然后您使用str 将其调整回字符串(在尝试用逗号替换空格之前)。这会给你方括号和引号,你可能不想要,而且你会得到一堆额外的逗号。相反,我建议像这样使用str.join 方法:

    content = ",".join(content) # joins all members of the list with commas
    

    我不确定这是否是您想要的。使用split 将替换文件中的所有换行符,因此您将得到一行包含许多用逗号分隔的许多单词的行。

    【讨论】:

    • 内容是要在数组中使用的所有整数值。
    【解决方案2】:

    拆分内容时,忘记调用函数。同样,一旦你拆分,它就是一个数组,所以你应该循环替换东西。

    def file_get_contents(filename):
      with open(filename) as f:
        return f.read()
    
    content = file_get_contents('file.txt')
    content = content.split() <- HERE
    content = [c.replace(' ',',') for c in content]
    content = "".join(content)
    with open ('file.txt', 'w') as f:
      f.write(content)
    

    【讨论】:

    • split 之后不会有任何空格,所以replace 调用毫无意义。
    • 好点。只需按照答案中的代码即可。我认为意图可能是进行一些实际的替换。
    【解决方案3】:

    如果您要替换字符,我认为您最好使用 python 的 re 模块进行正则表达式。示例代码如下:

    import re
    
    def file_get_contents(filename):
      with open(filename) as f:
        return f.read()
    
    if __name__=='__main__':
        content = file_get_contents('file.txt')
        # First replace any spaces with commas, then remove any other whitespace
        new_content = re.sub('\s', '', re.sub(' ', ',', content))
        with open ('new_file.txt', 'w') as f:
          f.write(new_content)
    

    它比一直尝试拆分更简洁,并为您提供更多灵活性。还要注意您使用代码打开和读取的文件有多大 - 您可能需要考虑使用行迭代器或其他东西,而不是一次读取所有文件内容

    【讨论】:

      猜你喜欢
      • 2014-05-17
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多