打开不同目录下的所有文件python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18389946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:37:31  来源:igfitidea点击:

Open all files in different directory python

pythonpython-3.x

提问by hjames

I need to open a file from a different directory without using it's path while staying in the current directory.

我需要从不同目录打开文件而不使用它的路径,同时停留在当前目录中。

When I execute the below code:

当我执行以下代码时:

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

I get the error message FileNotFoundError: [Errno 2] No such file or directory:because it's in a sub directory.

我收到错误消息,FileNotFoundError: [Errno 2] No such file or directory:因为它位于子目录中。

Question: Is there an os command I can use that will locate and open the file in sub_dir?

问题:是否有我可以使用的 os 命令来定位和打开文件sub_dir

Thanks! -let me know if this is a repeat, I searched and couldn't find one but may have missed it.

谢谢!-让我知道这是否是重复的,我搜索过但找不到,但可能已经错过了。

采纳答案by Martijn Pieters

os.listdir()lists onlythe filename without a path. Prepend these with sub_diragain:

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

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

If all you are doing is loop over the lines from the file, just loop over the file itself; using withmakes sure that the file is closed for you when done too. Last but not least, str.replace()returnsthe new string value, not change the value itself, so you need to store that return value:

如果您所做的只是遍历文件中的行,只需遍历文件本身即可;usingwith确保在完成后为您关闭文件。最后但并非最不重要的是,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=", ", ")

回答by Saullo G. P. Castro

You must give the full path if those files are not in the current directory:

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

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

I would not use fileas a variable name, maybe filename, since this is used to create a file object in Python.

我不会将其file用作变量名,也许是filename,因为它用于在 Python 中创建文件对象。

回答by Rahul Telgote

Code to copy files using shutil

使用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)