2016-03-01 76 views
0

我做了一个简单的程序来测试。它只是查找特定字符串的任何实例,并用新字符串替换它。我想要做的是对我的整个目录,逐个文件地运行这个。在目录上运行一个简单的脚本

def replace(directory, oldData, newData): 
    for file in os.listdir(directory): 
     f = open(file,'r') 
     filedata = f.read() 
     newdata = filedata.replace(oldData,newData) 
     f = open(file, 'w') 
     f.write(newdata) 
     f.close() 

但我不断收到一条错误消息,告诉我一个文件不存在于我的目录中,即使它存在。我无法弄清楚为什么它会告诉我。

+3

'os.listdir'仅返回文件名,他们没有目录前缀。使用'os.path.join'连接它们。 – Barmar

回答

1

os.listdir()返回一个非常类似于终端命令ls的字符串列表。它列出了文件的名称,但不包括目录的名称。您需要在自己加入与os.path.join()

def replace(directory, oldData, newData): 
    for file in os.listdir(directory): 
     file = os.path.join(directory, file) 
     f = open(file,'r') 
     filedata = f.read() 
     newdata = filedata.replace(oldData,newData) 
     f = open(file, 'w') 
     f.write(newdata) 
     f.close() 

我不会推荐file作为变量名,但是,因为它具有内置式冲突。另外,建议在处理文件时使用with块。以下是我的版本:

def replace(directory, oldData, newData): 
    for filename in os.listdir(directory): 
     filename = os.path.join(directory, filename) 
     with open(filename) as open_file: 
      filedata = open_file.read() 
      newfiledata = filedata.replace(oldData, newData) 
      with open(filename, 'w') as write_file: 
       f.write(newfiledata) 
1

试试这个方法:

def replace(directory, oldData, newData): 
    for file in os.listdir(directory): 
     f = open(os.path.join(directory, file),'r') 
     filedata = f.read() 
     newdata = filedata.replace(oldData,newData) 
     f = open(os.path.join(directory, file), 'w') 
     f.write(newdata) 
     f.close() 
相关问题