在Python中打开不同目录中的所有文件

9

我需要在当前目录下打开另一个目录中的文件,但不使用其完整路径。

当我执行以下代码时:

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:,因为它在子目录中。

问题:是否有一个可以定位并打开sub_dir文件的操作系统命令?

谢谢! - 如果这是重复的,请告诉我,我搜索了但找不到,可能是我错过了。


你需要在open()函数中添加sub_dir路径才能打开文件。 - user1593705
3个回答

13

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=", ", ")

如果我想将新行写入filename,我需要添加f.write(line)并在a模式下打开吗? - hjames
@hjames:当然,只需调整open()调用的mode参数即可。 - Martijn Pieters
嗯,如果我将其放在aw模式下,它会返回一个错误,表示文件不可读。如果我将其放在r模式下,显然无法写入文件。 - hjames
io.UnsupportedOperation: 不可读取io.UnsupportedOperation: 不可写入 - hjames
1
@hjames:你需要同时以读写方式打开文件吗?那么请使用r+w+(打开现有文件,r将保留现有数据,w将截断现有文件)。 - Martijn Pieters

11

如果这些文件不在当前目录中,您必须提供完整的路径:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接