初级Python:将GLOB结果写入tx

2024-10-01 07:47:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个文本文件的路径和文件名的所有在一个证书目录。环顾四周之后,看起来最好的方法是使用GLOB函数,我可以编写一个代码,其中包含每个文件的路径列表:

import glob
dirlist = glob.glob('P:\MyDep\Myunit\MySection\Stuff\Reports\YR*\O*\*\*\*\*.pdf')
Bureau\Traffic\Reports\YR*\R*\*\*.pdf')
fo=open('new.txt', "w")
fo.write('\n'.join(dirlist))
fo.close()

然而,我发现自己使用excel的MID statement从报告中提取值。理想情况下,我希望文件的基名包含在路径中作为元组。我提出了以下建议:

^{pr2}$

但我似乎无法将结果写入文本文件:我能做的最好的事情似乎是从dirtup生成一个包含一个列表的文本文件(经过编辑以显示带有建议的代码):

import glob, os
for f in f in glob.glob('P:\MyDep\Myunit\Mysection\Stuff\Reports\YR*\O*\*\*\*\*.pdf'):
    fpath, fname = os.path.split(f)
    rname, extname = os.path.splitext(fname)
    dirtup = (f, rname)
    fo=open('axlspd.txt', "w")
    fo.write(', '.join(dirtup)+'\n')
    fo.close()

如何将dirtup的所有结果放入文本文件?提前谢谢。在


Tags: 文件代码import路径列表pdfosglob
3条回答

我看不出你的问题:

>>> import glob
>>> for f in glob.glob(r'c:\*.dll'):
...     print f
...
c:\install.res.1028.dll
c:\install.res.1031.dll
c:\install.res.1033.dll
c:\install.res.1036.dll
c:\install.res.1040.dll
c:\install.res.1041.dll
c:\install.res.1042.dll
c:\install.res.2052.dll
c:\install.res.3082.dll
c:\msdia80.dll
>>> import os
>>> for f in glob.glob(r'c:\*.dll'):
...    fpath, fname = os.path.split(f)
...    rname, extname = os.path.splitext(fname)
...    dirtup = (f, rname)
...    print dirtup
...
('c:\\install.res.1028.dll', 'install.res.1028')
('c:\\install.res.1031.dll', 'install.res.1031')
('c:\\install.res.1033.dll', 'install.res.1033')
('c:\\install.res.1036.dll', 'install.res.1036')
('c:\\install.res.1040.dll', 'install.res.1040')
('c:\\install.res.1041.dll', 'install.res.1041')
('c:\\install.res.1042.dll', 'install.res.1042')
('c:\\install.res.2052.dll', 'install.res.2052')
('c:\\install.res.3082.dll', 'install.res.3082')
('c:\\msdia80.dll', 'msdia80')
>>>

除非在将元组写入文件时遇到问题。试试这个:

^{pr2}$

我认为os.walk更适合这样:

import os
for root,dirs,files in os.walk('.'):
   #                            ^ Name of directory where you start your file search
   for f in files:
       print root,os.path.join(root,f)  #writes it as path path/filename

看起来您只需要以“.pdf”结尾的文件,为此,我们可以先筛选文件名,然后将其放入文本文件也很容易:

^{pr2}$

问题是您多次打开该文件。使用'w'标志,文件每次打开时都会被截断,您只能看到最后一次写入。在

在循环之前打开文件,然后在循环之后关闭文件,或者使用新的fangled with语句:

import glob, os
with open('axlspd.txt', "w") as axlspd:
    for f in f in glob.glob('P:\MyDep\Myunit\Mysection\Stuff\Reports\YR*\O*\*\*\*\*.pdf'):
        fpath, fname = os.path.split(f)
        rname, extname = os.path.splitext(fname)
        dirtup = (f, rname)
        axlspd.write(', '.join(dirtup)+'\n')

退出该代码块时,文件将自动关闭。在


这是您错过的引用:http://docs.python.org/library/functions.html#open

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists)

相关问题 更多 >