繁体   English   中英

python —尝试更改文件的内容

[英]python — trying to change the contents of a file

我有一个名为“ hello.txt”的文件,其内容为“ Hello,there!”。 我要删除“,”和“!” 然后打印新内容。

使用我编写的代码,该程序可以正常运行,但是会擦除所有内容并留下一个空文件。

def myfunc(filename):
filename=open('hello.txt','r')  
lines=filename.readlines()
filename.close()
filename=open('hello.txt','w')
for line in lines:
     for punc in ".!":
        line=line.replace(punc,"")
filename.close()


myfunc("hello")

请不要使用高级命令。 谢谢!

您应该一行一行地打印修改后的内容,而不仅仅是在最后。

for line in lines:
    for punc in ",!":

        # note that we're assigning to line again
        # because we're executing this once for
        # each character
        line=line.replace(punc,"")

    # write the transformed line back to the file once ALL characters are replaced
    #
    # note that line still contains the newline character at the end

    # python 3
    # print(line,end="")

    # python 2.x
    print >> filename, line,

    # python 2.x alternative
    # filename.write(line)

顺便说一句,命名文件句柄 filename是令人困惑的。

您正在更改程序中的行,但未写入文件。 在更改行之后,尝试使用filename.writelines(lines)

您可以使用正则表达式模块。 替换很容易:

import re
out = re.sub('[\.!]', '', open(filename).read())
open(filename, 'w').write(out)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM