简体   繁体   English

如何从文件中读取并将其作为整数放入列表中? Python

[英]How do I read from a file and put it into a list as an integer? Python

This is what I have这就是我所拥有的

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

I would line to convert each line into an integer in the for line in file: How do I do this?我会在文件中的 for 行中将每一行转换为整数:我该怎么做?

Optional: And If I have non numerical character in numberlist.txt ?可选:如果我在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 :如果每一行都有一位数字,则可以直接使用文件对象map函数:

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

Notes : never use of python built-in names as your variable names and also open your file with with statement.注意:永远不要使用 python 内置名称作为变量名,也不要使用with语句打开文件。

The with statement is used to wrap the execution of a block with methods defined by a context manager. with 语句用于用上下文管理器定义的方法包装块的执行。

Read more about the with statement and its usage advantage.阅读有关with语句及其使用优势的更多信息。 https://docs.python.org/2/reference/compound_stmts.html https://docs.python.org/2/reference/compound_stmts.html

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.但是,如果根据文件的外观,文件中可能有非数字字符,则可以使用一些方法,例如可以使用try-except语句完成的exception-handling

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!请注意,这可能有很多场景,根据您的代码,您可以使用各种方法!

you can use the int constructor or type-caster if you will, to convert string to integer.如果愿意,您可以使用int构造函数或 type-caster 将字符串转换为整数。 it throws a ValueError if the conversion is not possible.如果转换不可能,它会抛出一个ValueError

int_value = int(strvalue)

a good way to do the same operation on all elements in a list in python is to use the map function.在python中对列表中的所有元素执行相同操作的一个好方法是使用map函数。 do a help(map) in the interpreter to see how it works在解释器中做一个help(map)看看它是如何工作的

# assuming that the file exists
file = open("numberlist.txt")
my_list = []
for line in file:
        line = line.strip()
        list.append(line)
try:
    list_of_ints = map(int, my_list)
except ValueError:
    print("invalid file")

to check if the list is proper, put the operation in a try-except block.要检查列表是否正确,请将操作放在 try-except 块中。

you can do all of this in a couple of lines by using the with statement您可以使用with语句在几行中完成所有这些操作

with open("numbers.txt") as file_object:
    try:
        list_of_ints = map(int, (l.strip() for l in file_object))
    except ValueError:
        print("invalid file")

here i am using file_object as an iterable (it gives all the lines in the file).在这里,我使用 file_object 作为可迭代对象(它给出了文件中的所有行)。 and using the generator syntax to create another iterable on which to apply the map function并使用生成器语法创建另一个可应用 map 函数的可迭代对象

file = open("numberlist.txt",'r')
l = []

for line in file:
    line = line.split()
    try:
        l.append(int(line[0]))
    except:
        continue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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