python打开相对文件夹中所有以.txt结尾的文件
python open all files ending with .txt in a relative folder
我需要打开并解析文件夹中的所有文件,但我必须使用相对路径(类似于 ../../input_files/)。
我知道在JavaScript你可以使用“路径”库来解决这个问题。
如何在 python 中完成?
可以使用os
库中的listdir
,只过滤掉以txt为结尾的文件
from os import listdir
txts = [x for x in listdir() if x[-3:] == 'txt']
然后您可以遍历列表并对每个文件进行处理。
这样你就可以得到一个路径中的文件列表作为一个列表
您还可以过滤文件类型
import glob
for file in glob.iglob('../../input_files/**.**',recursive=True):
print(file)
这里可以指定文件类型:**.**
例如:**.txt
输出:
../../input_files/name.type
不用担心绝对路径,下面一行为您提供了运行脚本的绝对路径。
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir to the script is in
现在您可以将相对路径合并为绝对路径
rel_path = 'relative_path_to_the_txt_dir'
os.path.join(script_dir, rel_path) # <-- absolute dir to the txt is in
如果您打印以上行,您将看到 txt
文件所在的确切路径。
这是您要查找的内容:-
import glob
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir to the script is in
rel_path = 'relative_path_to_the_txt_dir'
txt_dir = os.path.join(script_dir, rel_path) # <-- absolute dir to the txt is in
for filename in glob.glob(os.path.join(txt_dir, '*.txt')): # filter txt files only
with open(os.path.join(os.getcwd(), filename), 'r') as file: # open in read-only mode
# do your stuff
这里有几个链接,你可以理解我做了什么:-
参考文献:-
- Open file in a relative location in Python
- How to open every file in a folder
我需要打开并解析文件夹中的所有文件,但我必须使用相对路径(类似于 ../../input_files/)。
我知道在JavaScript你可以使用“路径”库来解决这个问题。
如何在 python 中完成?
可以使用os
库中的listdir
,只过滤掉以txt为结尾的文件
from os import listdir
txts = [x for x in listdir() if x[-3:] == 'txt']
然后您可以遍历列表并对每个文件进行处理。
这样你就可以得到一个路径中的文件列表作为一个列表
您还可以过滤文件类型
import glob
for file in glob.iglob('../../input_files/**.**',recursive=True):
print(file)
这里可以指定文件类型:**.**
例如:**.txt
输出:
../../input_files/name.type
不用担心绝对路径,下面一行为您提供了运行脚本的绝对路径。
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir to the script is in
现在您可以将相对路径合并为绝对路径
rel_path = 'relative_path_to_the_txt_dir'
os.path.join(script_dir, rel_path) # <-- absolute dir to the txt is in
如果您打印以上行,您将看到 txt
文件所在的确切路径。
这是您要查找的内容:-
import glob
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir to the script is in
rel_path = 'relative_path_to_the_txt_dir'
txt_dir = os.path.join(script_dir, rel_path) # <-- absolute dir to the txt is in
for filename in glob.glob(os.path.join(txt_dir, '*.txt')): # filter txt files only
with open(os.path.join(os.getcwd(), filename), 'r') as file: # open in read-only mode
# do your stuff
这里有几个链接,你可以理解我做了什么:-
参考文献:-
- Open file in a relative location in Python
- How to open every file in a folder