gpt4 book ai didi

python - 在Python中使用walk函数

转载 作者:行者123 更新时间:2023-12-01 06:00:00 25 4
gpt4 key购买 nike

我正在处理如下所示的文件夹层次结构:

c:/users/rox/halogen/iodine/(some .txt files)
c:/users/rox/halogen/chlorine/(some .txt files)
c:/users/rox/inert/helium/(some .txt files)
c:/users/rox/inert/argon/(some .txt files)

现在我正在使用 os.walk 遍历文件夹并处理文件。
但问题是,如果我想在分析“halogen”下的所有子文件夹后将分析输出生成到“halogen”文件夹,那么我应该做什么......我正在使用:

for root,dirs,files in os.walk(path,'*.txt):
.....
.......[processing file]
out.write(.....) # writing output in the folder which we are analyzing

但是如何将输出写入位于两步后面的文件夹(即卤素或惰性文件夹)..

最佳答案

在步行之前打开输出文件。

out = open(os.path.join(path, outputfilename), 'w')

然后走上处理输入的路径

for root,dirs,files in os.walk(path,'*.txt):
.....
out.write(..)

这样你就已经知道根路径了。否则,如果您确定您的道路只是后退两步。

os.path.join(current_path, '..', '..')

将为您提供文件夹路径,向后退两步

关于python - 在Python中使用walk函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10902695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com