如何在Python中使用文本文件中指定的通配符

0 投票
2 回答
526 浏览
提问于 2025-04-16 15:19

你好,我是Python的新手,我想知道如何逐行处理一个.txt文件,以便复制文件,这些文件是用通配符指定的。

基本上,这个.txt文件的内容是这样的。

bin/
bin/*.txt
bin/*.exe
obj/*.obj
document
binaries

现在有了这些信息,我想读取我的.txt文件,匹配目录,复制所有以*开头的文件到那个目录。同时,我也想复制.txt文件中列出的文件夹。有什么好的实际方法来做到这一点吗?谢谢你的帮助。

2 个回答

1

你可能想看看 glob 和 re 这两个模块。

http://docs.python.org/library/glob.html

2

这是一个可以开始的内容...

import glob # For specifying pathnames with wildcards
import shutil # For doing common "shell-like" operations.
import os # For dealing with pathnames

# Grab all the pathnames of all the files matching those specified in `text_file.txt`
matching_pathnames = []
for line in open('text_file.txt','r'):
    matching_pathnames += glob.glob(line)

# Copy all the matched files to the same filename + '.new' at the end
for pathname in matching_pathnames:
    shutil.copyfile(pathname, '%s.new' % (pathname,))

撰写回答