程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了python 打开相对文件夹中所有以 .txt 结尾的文件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决python 打开相对文件夹中所有以 .txt 结尾的文件?

开发过程中遇到python 打开相对文件夹中所有以 .txt 结尾的文件的问题如何解决?下面主要结合日常开发的经验,给出你关于python 打开相对文件夹中所有以 .txt 结尾的文件的解决方法建议,希望对你解决python 打开相对文件夹中所有以 .txt 结尾的文件有所启发或帮助;

我需要打开并解析文件夹中的所有文件,但我必须使用相对路径(例如../../input_files/)。

我知道在 JavaScript 中你可以使用“路径”库来解决这个问题。

我如何在 python 中做到这一点?

解决方法

这样你就可以得到一个路径中的文件列表作为列表

您还可以过滤文件类型

import glob

for file in glob.iglob('../../input_files/**.**',recursive=True):
    print(file)

这里可以指定文件类型:**.**

例如:**.txt

输出:

../../input_files/name.type

,

您可以使用 listdir 库中的 os,只过滤掉以 txt 结尾的文件

from os import listdir
txts = [x for x in listdir() if x[-3:] == 'txt']

然后您可以遍历列表并对每个文件进行处理。

,

不要担心绝对路径,下面的行为您提供了脚本运行的绝对路径。

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

这里有几个链接,你可以理解我做了什么:-

  1. os.path.dirname(path)
  2. os.path.join(path,*paths)
  3. glob.glob(pathname,*,recursive=False)

参考文献:-

  1. Open file in a relative location in Python
  2. How to open every file in a folder

大佬总结

以上是大佬教程为你收集整理的python 打开相对文件夹中所有以 .txt 结尾的文件全部内容,希望文章能够帮你解决python 打开相对文件夹中所有以 .txt 结尾的文件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: