简体   繁体   中英

Generating multiple .txt files from a single .csv?

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

ABCD

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM