gpt4 book ai didi

python - 写入文件并维护文件夹结构

转载 作者:行者123 更新时间:2023-11-30 23:23:19 25 4
gpt4 key购买 nike

我正在编写一个脚本,该脚本将从一个位置读取文件,操作数据,然后将输出写入到不同的位置。在命令行中,用户将使用 -p 指定顶级文件夹,然后脚本将递归到该文件夹​​并查找所有文件。我现在正在使用 glob 执行此操作,并且文件的读取效果很好。

但我还希望用户指定一个输出文件夹来写入文件,并且我想维护输入路径的文件夹结构。

for eachFile in glob(args.path + "/*/*.json"): <- this seems dangerous. Better way?
# do something to the json file

# output the modified data to its new home
#outfile = os.path.join(args.output, os.path.dirname(eachFile), eachFile) <- doesn't work
outfile = os.path.join(args.putout, os.path.dirname(eachFile)[1:], eachFile)

最后一行是我做过的最好的一行,但是当它去掉目录前面的 "/" 时,它会假设这是在 posix 机器上运行的问题。另外,假设我传入 ~/Documents/2014 输入路径和 /tmp 输出。这些文件将写入 /tmp/Users/myusername/Documents/2014/blah/whatever.json

这似乎是一个相当常见的用例,所以我很惊讶我没有找到其他人需要执行此操作或可以轻松完成此操作的简单模块。有什么建议吗?

最佳答案

这是一个接近您需要的脚本。这里的关键是,您需要 os.walk 而不是 glob,因为您想深入了解目录结构。您需要添加健全性检查,但这是一个好的开始。

# Recurse and process files.
import os
import sys
from fnmatch import fnmatch
import shutil


def process(src_dir, dst_dir, pattern='*'):
"""Iterate through src_dir, processing all files that match pattern and
store them, including their parent directories in dst_dir.
"""
assert src_dir != dst_dir, 'Source and destination dir must differ.'
for dirpath, dirnames, filenames in os.walk(src_dir):
# Filter out files that match pattern only.
filenames = filter(lambda fname: fnmatch(fname, pattern), filenames)

if filenames:
dir_ = os.path.join(dst_dir, dirpath)
os.makedirs(dir_)
for fname in filenames:
in_fname = os.path.join(dirpath, fname)
out_fname = os.path.join(dir_, fname)

# At this point, the destination directory is created and you
# have a valid input / output filename, so you'd call your
# function to process these files. I just copy them :D
shutil.copyfile(in_fname, out_fname)

if __name__ == '__main__':
process(sys.argv[1], sys.argv[2], '*.txt')

关于python - 写入文件并维护文件夹结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24040640/

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