【问题标题】:How to delete a specific character automatically from a text file using Python?如何使用 Python 从文本文件中自动删除特定字符?
【发布时间】:2020-08-20 22:11:41
【问题描述】:

我正在尝试为项目使用一些代码来获取一组字母数字字符的组合并将它们写入 .txt 文件。当我从我的设备打开文件时,它显示以下内容:

[aaaa
[aaab
[aaac
...
]fh52
...

代码应该只是输出字母和数字,没有其他字符,但它仍然是。我可以处理具有这些“工件”的 .txt 文件,但我需要一种在未来使用 Python 删除这些工件的方法。

我认为代码应该是这样的:

unwanted_chars="[]"
datafile=open("Combinations.txt", 'a+')
for line in datafile:
    for char in line:
        if char in unwanted_chars:
            line.replace(char,"")

非常感谢您对此的任何帮助。

【问题讨论】:

  • 您从未更改过文件。您所更改的只是内存中行的副本——您必须在进行更改后将数据写回文件。请阅读有关文件读取和写入的教程,以了解这些内容是如何工作的。

标签: python string replace char text-files


【解决方案1】:

你已经接近了。首先,您不需要 if 声明。其次,strreplace 方法不会改变现有的项目,所以你的最后一行没有做任何事情。您需要读入文件,替换字符,然后将其写回。

with open('Combinations.text') as f:
    lines=list(f)
for k, line in enumerate(lines):
    for c in unwanted_chars:
        line=line.replace(c,'')
    lines[k]=line

with open('Combinations.text','w') as f:
    f.write('\n'.join(lines))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    相关资源
    最近更新 更多