簡體   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