简体   繁体   中英

Convert several CSV files into several TXT files with the same name

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')

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM