【问题标题】:.write() not writing anything to ouput file python.write() 不向输出文件 python 写入任何内容
【发布时间】:2019-02-28 10:46:34
【问题描述】:

所以我试图打开一个目录中的一堆文件,从这些文件中删除一些单词并将输出写入同一目录中的文件。尝试写入输出文件时遇到问题。没有任何内容写入文件。任何尝试解决此问题的帮助将不胜感激!这是我的代码:

path = 'C:/Users/User/Desktop/mini_mouse'
output = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(path):
    for file in files:
        #print(os.getcwd())
        #print(file)
        os.chdir(path)
        #print(os.getcwd())
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            #x = ''
            mouse_file = f.read().split()  # reads file and splits it into a list
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            #print(x)
            with open(output, 'w') as output_file:
                output_file.write(x)

【问题讨论】:

  • 您正在对哪些文件执行类似文本的操作
  • 假设输出是你的输出文件,with open(output, 'w') as output_file:
  • 也许你希望写信给C:/Users/User/Desktop/filter_mini_mouse/mouse,但在你的open语句中,你写的是一个名为out的文件。
  • 你们说得对,我实际上想将输出写入“C:/Users/User/Desktop/filter_mini_mouse/mouse”,即我命名的输出。我仍然遇到同样的问题,但是,正在创建文件,但其中没有任何内容。

标签: python file output nltk file-handling


【解决方案1】:

每次使用循环中的'w' 模式打开文件时,都会擦除文件的内容。因此,按照您的代码的方式,如果您的最后一次循环迭代产生一个空结果,您将不会在文件中看到任何内容。

将模式改为'w+''a'

        with open(output, 'w+') as output_file:

Reading and Writing Files:

mode 可以是 'r' 表示只读取文件,'w' 表示只写入(已存在的同名文件将被删除),'a' 打开文件进行追加;

【讨论】:

  • 非常感谢!使用“a”对我有用!再次感谢您!
猜你喜欢
  • 1970-01-01
  • 2018-12-01
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多