Reputation: 111
I'm new to Python and am having a difficult time figuring out how to write a program that will write out a single .txt file for every line in a .csv file. For instance, I have the following .csv file with data from multiple calculations and I need .txt files created for each individual calculation. Formatting is rough to do here but the bold letters are column names and corresponding elements are underneath (ex: "Run2 and "20" belong to column C).
A B C D
Title: Run1 Run 2 Run3
"Initial Composition: FeO" 10 20 30
"Initial Composition: MgO" 40 50 60
I want my Python code to output the following:
1.txt:
Title: Run 1
Initial Composition: FeO 10
Initial Composition: Mgo: 40
2.txt:
Title: Run 2
Initial Composition: FeO 20
Initial Composition: Mgo: 50
The elements from A need to be printed in every .txt file with numbers from various calculations contained in columns B, C, etc... printed beside with a space. Bonus points for anyone who can also help me create custom filenames for the .txt files based on the title (ex: the data from column A creates a .txt file called "Run1.txt." Don't know if assigning each column to a dictionary and then appending them all together would be the best route?
Thank you!
Upvotes: 0
Views: 402
Reputation: 21
Something like this:
with open('runs.csv','rb') as read_file:
reader = csv.reader(read_file)
for run in reader:
with open(run[0] + '.txt','wb') as write_file:
write_file.write(run[1] + '\n')
For a csv file with the format "Name of file","Run results", obviously this can be replaced with anything you want.
Upvotes: 1