I have multiple .txt files and I want to convert them to .csv files with the same name. The filename for these .txt files is something like this:
01-09-2022-something.txt
02-09-2022-something.txt
03-09-2022-something.txt
04-09-2022-something.txt
.
.
.
.
31-09-2022-something.txt
I need to convert files like these to .csv but with the same name. Can anyone help me with this ?
Currently, I wrote this code to convert but for this, I have to know the file name and in my case filename is not static it is dynamic.
import pandas as pd
file_path = "/var/opt/something.txt"
dataframe1 = pd.read_csv(file_path, delim_whitespace=True)
dataframe1.to_csv('something.csv', index = None)
CodePudding user response:
import os
my_txt_files = [i for i in os.listdir('/var/opt') if i[-4:] == '.txt']
with open('/var/opt/something.csv', 'w') as out_f:
for txt in my_txt_files:
with open('/var/opt/' txt, 'r') as in_f:
out_f.write(in_f.read())
CodePudding user response:
Use for
-loop with os.listdir()
or glob.glob("*.txt")
And use new_path = file_path.replace('.txt', '.csv')
If you don't want to change data inside file then use os.rename()
import glob
import os
for file_path in glob.glob("/var/opt/*.txt")
new_path = file_path.replace('.txt', '.csv')
os.rename(file_path, new_path)
And if you want to make changes in data then use pandas
import pandas as pd
import glob
import os
for file_path in glob.glob("/var/opt/*.txt")
new_path = file_path.replace('.txt', '.csv')
df = pd.read_csv(file_path, delim_whitespace=True)
# ... some changes ...
df.to_csv(new_path, index=None)