将多个 CSV 文件转换为多个同名的 TXT 文件
我正在尝试从多个 .csv 文件获取所有“链接”数据,并使用这些链接数据创建 .txt 文件,而不合并到一个文件(当前为 result_df.txt)。第一步效果很好! (谢谢 Ali!)但我想将我的几个 csv 文件的名称(每个名称都不同)保留到这些 txt 文件中。
name1.csv -->名称1.txt
name2.csv --> name2.txt
name3.csv --> name3.txt
...
请问这里有什么建议吗?
非常感谢
from os.path import abspath, join
from os import listdir
import pandas as pd
result_df = pd.DataFrame(columns=['link'])
abs_path = abspath(path) # path of your folder
for filename in listdir(abs_path):
df = pd.read_csv(join(abs_path, filename), usecols=['link'])
result_df = pd.concat([result_df, df], ignore_index=True)
result_df.to_csv('result_df.txt', header=None, index=None, sep=' ', mode='w')
I'm trying to get all 'link' data from several .csv files and create .txt files with these links data without merging into one file (currently result_df.txt) . First step works well! (thanks Ali!) but I would like to keep the name of my several csv files (each name are different) into these txt files.
name1.csv --> name1.txt
name2.csv --> name2.txt
name3.csv --> name3.txt
...
Any suggestions here please?
Many thanks
from os.path import abspath, join
from os import listdir
import pandas as pd
result_df = pd.DataFrame(columns=['link'])
abs_path = abspath(path) # path of your folder
for filename in listdir(abs_path):
df = pd.read_csv(join(abs_path, filename), usecols=['link'])
result_df = pd.concat([result_df, df], ignore_index=True)
result_df.to_csv('result_df.txt', header=None, index=None, sep=' ', mode='w')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么你为什么要 concat 呢?只需保存到 .txt 文件并更新名称
df.to_csv(filename[:-4] + '.txt')
So why do you concat ? just save to .txt file updating the name
df.to_csv(filename[:-4] + '.txt')