2013-08-22 40 views
9

我需要从不同目录中打开一个文件,而不必使用它的路径,而停留在当前目录中。打开不同目录中的所有文件python

当我执行下面的代码:

for file in os.listdir(sub_dir): 
    f = open(file, "r") 
    lines = f.readlines() 
    for line in lines: 
     line.replace("dst=", ", ") 
     line.replace("proto=", ", ") 
     line.replace("dpt=", ", ") 

我得到错误信息FileNotFoundError: [Errno 2] No such file or directory:,因为它是在一个子目录。

问题:是否有一个os命令我可以使用它将找到并打开文件sub_dir

谢谢! - 我知道这是否是重复的,我搜索了并找不到一个,但可能错过了它。

+0

您需要将sub_dir路径添加到在open()函数的文件能够打开它来复制文件。 – 2013-08-22 20:14:42

回答

11

os.listdir()列表只有没有路径的文件名。与sub_dir再在前面加上这些:

for filename in os.listdir(sub_dir): 
    f = open(os.path.join(sub_dir, filename), "r") 

如果你正在做的是循环遍历从文件,在文件本身只是环行;使用with确保文件在完成时也关闭。最后但并非最不重要的,str.replace()回报新的字符串值,不改变本身的价值,所以你需要存储返回值:

for filename in os.listdir(sub_dir): 
    with open(os.path.join(sub_dir, filename), "r") as f: 
     for line in f: 
      line = line.replace("dst=", ", ") 
      line = line.replace("proto=", ", ") 
      line = line.replace("dpt=", ", ") 
+0

如果我想将新行写入'filename',我会添加'f.write(line)'并以'a'模式打开吗? – hjames

+0

@hjames:当然,只需调整'open()'调用的'mode'参数即可。 –

+0

嗯,如果我把它放在'a'或'w'模式下,它会返回一个文件不可读的错误。如果我把它放在'r'模式下,它显然不能写入文件。 – hjames

10

如果这些文件不在当前必须给出完整路径目录:

f = open(os.path.join(sub_dir, file)) 

我不会用file作为变量名,也许filename,因为这是用来在Python中创建一个文件对象。

-1

代码中使用shutil

import shutil 
import os 

source_dir = "D:\\StackOverFlow\\datasets" 
dest_dir = "D:\\StackOverFlow\\test_datasets" 
files = os.listdir("D:\\StackOverFlow\\datasets") 

if not os.path.exists(dest_dir): 
    os.makedirs(dest_dir) 

for filename in files: 
    if file.endswith(".txt"): 
     shutil.copy(os.path.join(source_dir, filename), dest_dir) 

print os.listdir(dest_dir) 
相关问题