Python:读写多个文件

时间:2016-12-05 01:48:59

标签: python python-2.7

import sys
import glob
import os.path

list_of_files = glob.glob('/Users/Emily/Topics/*.txt') #500 files

for file_name in list_of_files:
    print(file_name)

f= open(file_name, 'r')
lst = []
for line in f:
   line.strip()
   line = line.replace("\n" ,'')
   line = line.replace("//" , '')
   lst.append(line)
f.close()

f=open(os.path.join('/Users/Emily/UpdatedTopics',
os.path.basename(file_name)) , 'w')

for line in lst:
   f.write(line)
f.close()

我能够读取我的文件并进行一些预处理。我面临的问题是,当我把文件写出来时,我只能看到一个文件。我应该得到500个文件。

2 个答案:

答案 0 :(得分:4)

Python使用缩进而不是花括号来帮助分组代码。现在你的代码缩进的方式,Python正在解释它:

# get list of files
list_of_files = glob.glob('/Users/Emily/Topics/*.txt') #500 files

# loop through all file names
for file_name in list_of_files:
    # print the name of file
    print(file_name)

# PROBLEM: you remove your indentation so we are no longer in
# our for loop.  Now we take the last value of file_name (or the
# last file in the list) and open it and then continue the script
f= open(file_name, 'r')
...

请注意,由于缩进的更改,我们将保留for循环。脚本的其余部分仅在for循环中打开的最后一个文件上运行。

答案 1 :(得分:0)

试试这个

import os
path = "/Users/Emily/Topics/"
for root,dirs,files in os.walk(path):
   for dir in dirs:
       write_files = [os.path.join(dir) + ".txt"]
       for wf in write_files:
           with open(wf,"w") as outfile: