Home > database >  Convert several CSV files into several TXT files with the same name
Convert several CSV files into several TXT files with the same name

Time:03-02

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

CodePudding user response:

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