将多个 CSV 文件转换为多个同名的 TXT 文件

发布于 2025-01-11 00:30:49 字数 770 浏览 0 评论 0原文

我正在尝试从多个 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪漫之都 2025-01-18 00:30:49

那么你为什么要 concat 呢?只需保存到 .txt 文件并更新名称 df.to_csv(filename[:-4] + '.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'])
  df.to_csv(filename[:-4] + '.csv')

So why do you concat ? just save to .txt file updating the name df.to_csv(filename[:-4] + '.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'])
  df.to_csv(filename[:-4] + '.csv')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文