如何打开要写入的文件,写入新信息,然后关闭文件?

时间:2012-11-08 22:59:14

标签: python file

  

可能重复:
  Replace four letter word in python

我想在python shell中写一个文件,在其中运行一个程序,然后关闭该文件。

这是我现在的代码。

def censor(fileName):
    file = open(fileName, "r")
    for i in len(myList):
        censoredFile = open("censored.txt", "w")
        outputFile.write(censoredFile)
    outputFile.close()

我想要运行的程序还没有在程序中,因为我只想弄清楚如何处理文件。我有一些编程经验,但文件不是很多。任何意见都将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

这是您读取文件所需的代码,替换所有四个字母的单词并将最终结果写入不同的文件。

def censor(fileName):
    output_content = ""
    with open(fileName, "r") as input_file:
        with open("censored.txt", "w") as output_file:
            output_content = ""
            for line in input_file:
                output_content += ' '.join([word if len(word) != 4 else "****" for word in line.split(" ")])
            output_file.write(output_content)

应该是它。

答案 1 :(得分:0)

def censor(fileName):
    censoredFile = open("censored.txt", "w")
    for line in open(fileName, "r"):
        censoredLine= do_stuff_to_censor_line(line)
        censoredFile.write(censoredLine)

简单来说,这是函数的作用:

1. open the output file

2. go through the input file... for each line:
   2.1 figure out what the censored version of the line would be
   2.2 write the censored version of the line to the output file

3. close both files (this happens automatically so you dont actually have to call close()

现在实际审查一条线...... 如果你想要正确审查东西,只看4个字母的单词可能不够强大。这是因为并非所有顽皮的单词都是四个字母。还有一些不顽皮的单词,长达四个字母[例如:'四',' long',' want'' this' this' ;,'帮助']

def do_stuff_to_censor_line(line):
    list_of_naughty_words = ['naughty_word_1','naughty_word_2','etc']
    for naughty_word in list_of_naughty_words:
        line.replace(naughty_word,'*$#@!')
    return line

我会留给你处理不同的大写......

相关问题