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?
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)
Notes : never use of python built-in names as your variable names and also open your file with with
statement.
The with statement is used to wrap the execution of a block with methods defined by a context manager.
Read more about the with
statement and its usage advantage. 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.
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. it throws a ValueError
if the conversion is not possible.
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. do a help(map)
in the interpreter to see how it works
# 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.
you can do all of this in a couple of lines by using the with
statement
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). and using the generator syntax to create another iterable on which to apply the map function
file = open("numberlist.txt",'r')
l = []
for line in file:
line = line.split()
try:
l.append(int(line[0]))
except:
continue
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.