gpt4 book ai didi

python - 如何在 python 中将字符串数据帧转换为 csv?

转载 作者:行者123 更新时间:2023-12-04 10:11:50 35 4
gpt4 key购买 nike

我创建了一个程序,它使用 python glob 包获取目录中所有文件的名称

import glob

path = 'D:\Movies\American and Brit Cinema'

files = [f for f in glob.glob(path + "**/*.avi", recursive=True)]

for f in files:
print(f[35:])

我确实得到了我想要的输出:
The.Descendants.2011.
The.Expendables.2010.
The.Hangover.2009
The.Impossible.2012
the.invention.of.lying.2009
The.Muppets.2011.
The.Social.Network.2010
Tron.Legacy.2010

但是,我想获取这个电影标题列表并将其导出到 csv

当我尝试时,出现以下错误-
    f.to_csv('EnglishMovies.docx')

AttributeError: 'str' object has no attribute 'to_csv'

我也尝试转换为列表,但我得到的数据很乱。我只希望我的最终 csv 文件包含我目录中所有文件的名称

最佳答案

使用csv模块

import csv

with open('output.csv', mode='w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
for f in files:
writer.writerow([f])

关于python - 如何在 python 中将字符串数据帧转换为 csv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61300119/

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