Reputation: 55
I have a hudge csv file with 15 columns and a lot of lines.I use pandas
to keep only 5 columns in a new csv file.
new csv file.
ID, age, number of played game, ratio, Name
xx:xx:xx:xx:xx:xx, 19, 52, 33.0, GhostHotel
What i want to do is for each index value extract them from the entire line and print each value in a txt file.
expected task.
id.txt age.txt number_of_pg.txt ratio.txt Name.txt
I use the following code but this only print one value in a row.
import csv
with open('midvalues.csv') as player:
csv_reader = csv.reader(player)
for index, row in enumerate(csv_reader):
if index == 6:
print(row[4])
How can i save each value to his specific txt file ?
Upvotes: 1
Views: 85
Reputation: 86
You are aligned in the right direction with your code you just need to add some lines to make it work.
import csv
id = open(id.txt, 'a')
age = open(age.txt, 'a')
nop = open(number_of_pg.txt, 'a')
ratio = open(ratio.txt, 'a')
name = open(name.txt, 'a')
with open('midvalues.csv') as player:
csv_reader = csv.reader(player)
for index, row in enumerate(csv_reader):
id.write(f"{row[0]}\n")
age.write(f"{row[1]}\n")
nop.write(f"{row[2]}\n")
ratio.write(f"{row[3]}\n")
name.write(f"{row[4]}\n")
This code will print each element of a row separately in different files. you just need to create file empty files before execution of this code.
Upvotes: 1
Reputation: 261924
It looks like you want to save each column to a new file, so don't iterate rows, and use to_csv
:
for col in df:
df[col].to_csv(f'{col.replace(" ", "_")}.csv',
#index=False # uncomment to skip saving the index
)
Or, for custom names:
names = {'ID': 'id',
'age': 'age',
'number of played game': 'number_of_pg',
'ratio': 'ratio',
'Name': 'Name'}
for col, name in names.items():
df[col].to_csv(f'{name}.txt')
Example output for Name.txt
:
,Name
0,GhostHotel
Upvotes: 0