使用整数Python从列表写入文件 [英] Write to a file from a list with integer Python

查看:114
本文介绍了使用整数Python从列表写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从列表中写入文本文件,它与字符串列表完美配合,每个元素都换行了.但是,当我尝试从带有整数的列表中写入时,它不起作用. 问题是我需要将该列表作为整数列表放在代码的另一个位置(在if语句中比较值时),并且我尝试将整数列表转换为字符串列表,但随后将数字转换为整数列表被放置在单独的行上,例如

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 not work. The thing is I need that list as an integer-list in another place in the code (when comparing values in an if-statement), and I've tried to convert the integer-list to a string-list, but then the numbers gets placed on separate lines like for e.g.,

我必须用一行写2016年:

I have to write 2016 in one line:

2016

但是,它是这样的

2
0
1
6

这是用于写入文本文件的代码:

here is the code for writing to a text file:

print(写年份:") year.append(int(input()))

print("write year: ") year.append(int(input()))

...一些需要将列表年份作为整数的代码...

...some code that needs the list year as an integer...

year_string = str(年)

year_string = str(year)

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

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

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

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

推荐答案

#!/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)

给予

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

这就是你想要的吗?

这篇关于使用整数Python从列表写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆