Write to a file from a list with integer Python

后端 未结 3 1438
梦如初夏
梦如初夏 2021-01-23 17:18

Im trying to write a text file from a list, it works perfectly with a list of strings, each element gets on a new line. But when I try to write from a list with integers it does

相关标签:
3条回答
  • 2021-01-23 17:36
    #!/usr/bin/python
    
    years = [1,2,3,4,5,6,7,8,9,10]
    
    with open('year.txt', 'w') as file:
        for year in years:
            file.write("%i\n" % year)
    

    gives

    $ cat year.txt 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    Is that what you want?

    0 讨论(0)
  • 2021-01-23 17:42

    Since you used the variable name year I think you're trying to convert a string integer of year, so here's how you'd do that. I am also suspect this is the issue because of the odd output you're getting. I also added code on how to one-line convert years to a string version of itself.

    Writing an integer to a file

    year = 1998
    with open('year.txt', 'w') as file:
        file.write('\n'.join([str(year)]))
    

    Writing a list of integers to a file

    years = [1998,1996]
    with open('year2.txt', 'w') as file:
        file.write('\n'.join(str(year) for year in years))
    

    (Per request of the original poster):

    years = [1998,1996]
    with open('year2.txt', 'w') as file:
        file.write('\n'.join(years))
    
    0 讨论(0)
  • 2021-01-23 17:46

    You need to convert the integers to strings.

    with open('year_string.txt', 'w') as file:
    file.write('\n'.join(year_string))
    

    Needs to be:

    with open('year_string.txt', 'w') as file:
    file.write(str('\n'.join(year_string)))
    
    0 讨论(0)
提交回复
热议问题