简体   繁体   中英

I want to take numbers from a file and skip any string, after that i want to append every number inside one list. in python

so this is the file that I'm reading from I just want to extract the numbers from the file and put it in a list without taking any string along.

Salem Al Rashed
1200
Sara Al Kandari
950
Ahmad Al Fadli
1550

and this is the codes that I wrote but didn't work

my_list = []
file = open("employees.txt","r")    

for lines in file:
    if lines == ""
    slicing = int[lines]

You can do something like this:

f = open("employees.txt","r")
employees = f.read().split("\n")
f.close()

nums = []
for e in employees:
    try:
        nums.append(int(e))
    except ValueError:
        pass

print(nums)

Have a look at this article for some insight into parsing files with python: https://www.vipinajayakumar.com/parsing-text-with-python/

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.

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