0

In the code that I present, it reads csv files that are in one folder and prints them in another, I want this print to be with the same name that it has in the path but with an extension. For example, if the file is called: aaa.csv, the print would be aaa_ext.csv the print i get are file_list0.csv, file_list1.csv, file_list2.csv

This is my code:

import pandas as pd   
import numpy as np       
import glob   
import os  
all_files = glob.glob("C:/Users/Gamer/Documents/Colbun/Saturn/*.csv")   


file_list = []   
for i,f in enumerate(all_files):   
    df = pd.read_csv(f,header=0,usecols=["t","f"])
    df.to_csv(f'C:/Users/Gamer/Documents/Colbun/Saturn2/file_list{i}.csv') 
  • Also, semi-colons in python are only needed if you are providing a second statement on the same line. If you only have one statement in your line, drop the semi-colons. – Galo do Leste Feb 05 '23 at 05:54
  • 1
    You have put "file_list" inside string. Should be `df.to_csv(f'C:/Users/Gamer/Documents/Colbun/Saturn2/{file_list[i]}.csv')`. This presumes you have filled in file_list with the desired names and don't use an empty file like you have in your code. Or did you mean to use `df.to_csv(f'C:/Users/Gamer/Documents/Colbun/Saturn2/{f}_ext.csv') `. – Galo do Leste Feb 05 '23 at 06:02
  • Instead of using glob to make a list of the CSV files (hence `all_files` is a poor name) and then taking that list and iterating on it, you could just go ahead & iterate on all files & in the course of that use fnmatch to check for the files that match those with `.csv` extension and then act on those. That would put the file name as the current file name that you could then use similarly to options already provided, such as by Nova, to save the file with the new extension. Also see [here](https://stackoverflow.com/a/47496703/8508004) for some variations on how to do this, especially comments. – Wayne Feb 05 '23 at 06:27
  • Wayne, how would you put the code then?, thx for the comm – Isaac Rojas Oyarzun Feb 05 '23 at 07:04

1 Answers1

0

you can modify the line that writes the csv file as follows:

df.to_csv(f'C:/Users/Gamer/Documents/Colbun/Saturn2/{os.path.basename(f).split(".")[0]}_ext.csv') 
Nova
  • 406
  • 2
  • 13