我有以下代码,它打印出文件,但它没有将它分配给变量文件,以便我可以打开它
--update-section
答案 0 :(得分:1)
fnmatch
没有(并且不能)将file
扩展到正确的路径。它只是一个通配符模式测试。
os.listdir
返回文件 names 而不是文件 paths 。匹配文件名(正如您已经做的那样),但使用open
和您的源目录提供os.path.join
的完整路径:
the_dir = r'C:\Users\####\Documents\Visual Studio 2015\Projects\Data'
for file in os.listdir(the_dir):
if fnmatch.fnmatch(file, '*.csv'):
scanReport = open(os.path.join(the_dir,file))
或者最好在这种情况下使用glob.glob
来获取过滤器&绝对路径同时。
import glob
for file in glob.glob(r'C:\Users\####\Documents\Visual Studio 2015\Projects\Data\*.csv'):
scanReport = open(file)