我需要打开并解析文件夹中的所有文件,但我必须使用相对路径(类似../../input_files/(。
我知道在JavaScript中,您可以使用";路径";图书馆来解决这个问题。
我如何在python中做到这一点?
通过这种方式,您可以将路径中的文件列表作为列表
您还可以筛选文件类型
import glob
for file in glob.iglob('../../input_files/**.**',recursive=True):
print(file)
在这里您可以指定文件类型:**.**
例如:**.txt
输出:
..//input_files/name.type
不要担心Absolute路径,下面的行为您提供了运行脚本的Absolute通道。
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
这里有几个链接,你可以理解我做了什么:-
- os.path.dirname(路径(
- os.path.join(path,*paths(
- glob.glob(路径名,*,递归=False(
参考文献:-
- 在Python中的相对位置打开文件
- 如何打开文件夹中的每个文件
您可以使用os
库中的listdir
,并仅筛选出以txt作为结束的文件
from os import listdir
txts = [x for x in listdir() if x[-3:] == 'txt']
然后,您可以对列表进行迭代,并对每个文件进行处理。