【问题标题】:Iterating through txt files in directory, saving filenames遍历目录中的txt文件,保存文件名
【发布时间】:2021-01-04 02:53:07
【问题描述】:

我正在遍历目录中的文件,并希望保存文件名和我从同一 pandas 数据框中的文件中提取的一些内容。如何在浏览目录中的所有文件时将 txt 文件的名称保存在列表中(然后我会将其作为单独的列插入 pandas 数据框)?

这是我的部分代码:

columns_df = ['file', 'stuff']
df_stuff = pd.DataFrame(columns = columns_df)

filenamelist = []
stufflist = []

os.chdir(r'path\to\directory')
for file in glob.glob('*.txt'):
    # Extract some stuff from file and append to stufflist (DONE)
    # Save filename in the filenamelist (THE PROBLEM)

df_stuff['stuff'] = stufflist
df_stuff['file'] = filenamelist

【问题讨论】:

    标签: python pandas glob txt


    【解决方案1】:

    你需要这个功能吗?

    for file in glob.glob('*.txt'):
        filenamelist.append(file)
    

    【讨论】:

    • 我怎么没想到。如此简单,却如此有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多