如何读取文件并将其作为整数放入列表中? Python [英] How do I read from a file and put it into a list as an integer? Python

查看:119
本文介绍了如何读取文件并将其作为整数放入列表中? Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的

file = open("numberlist.txt")
list = []
for line in file:
      line = line.strip()
      list.append(line)

我要在文件的for行中将每一行转换为整数:我该怎么做?

I would line to convert each line into an integer in the for line in file: How do I do this?

可选:如果我在numberlist.txt中没有数字字符?我该如何测试并且必须编程告诉我文件不正确?

Optional: And If I have non numerical character in numberlist.txt? how can I test that and have to program tell me the file is not OK?

推荐答案

如果每行中只有一位,则可以直接使用

If you have one digit in each line you can directly use a file-object and map function :

with open("numberlist.txt") as f:
     num_list=map(int,f)

注意:切勿使用python内置名称作为变量名称,也不要使用with语句打开文件.

Notes : never use of python built-in names as your variable names and also open your file with with statement.

with语句用于使用上下文管理器定义的方法来包装块的执行.

The with statement is used to wrap the execution of a block with methods defined by a context manager.

阅读有关with语句及其使用优势的更多信息. https://docs.python.org/2/reference/compound_stmts.html

Read more about the with statement and its usage advantage. https://docs.python.org/2/reference/compound_stmts.html

但是,如果根据文件的外观,文件中可能包含非数字字符,则可以使用exception-handling之类的配方,可以通过try-except语句来完成.

But if you may have non numerical characters in your file based on whats your file look like you can use some recipes like exception-handling that it can be done with try-except statement.

因此,如果我们假设您在每一行中都有一个单词(包含数字或字符),您可以这样做

So if we suppose you have one word (contains digit or character) in each line you can do

num_list=[]
with open("numberlist.txt") as f:

  for line in f:
     try :
       num_list.append(int(line))
     except:
       continue #or other stuffs

注意,这可能有很多方案,根据您的代码,您可以使用各种方法!

Note that this can have a lot of scenarios and based on your code you can use various approaches!

这篇关于如何读取文件并将其作为整数放入列表中? Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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