简体   繁体   中英

how can i add two lists in a txt file so they stay in two different columns and are separated by a comma? (Python)

I am still a beginner in Python, but I really wanted to learn this. Until know I know how to imort files in Python, but I do not know how to export the data in .txt files. I have learned how to do this:

 file = open('file.txt', 'w')
 for item1 in x:
      print>>file, item1

where x is a list of numbers.

Anyone can suggest how to make export another list (let's say y) so that it gets printed parallel to the one I have here and possibly separated by a comma?

Thanks a lot!!

What you want to do is combine the two lists so the each element from one list is paired with the corresponding element of the other list. Once you do so, you can iterate over the combined list, and print out each element, separating them by comma:

a = [1, 2, 3]
b = [10, 20, 30]

combined = zip(a, b)   # combines 'a' and 'b' and produces
                       # [(1, 10), (2, 20), (3, 30)]

with open('file.txt', 'w') as handle:
    for row in combined:
        handle.write(','.join(map(str, row) + '\n')

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