Home > Back-end >  trying to create small programs to do simple calculations on data read in from text files
trying to create small programs to do simple calculations on data read in from text files

Time:01-28

As the title side, I am trying to create small programs to do simple calculations on data read in from text files. But I don't know how to turn the elements from the text file into integers. Any help would be greatly appreciated.

enter code heredef main():
f = input('enter the file name')
# this line open the file and reads the content f   '.txt' is required
getinfo = open(f  '.txt','r')
content = getinfo.read()
num = []

print('here are the number in your file',  num)
getinfo.close()

main ()

CodePudding user response:

If your .txt file is in this format,

1
2
3
4

Then you can use the split function on content like this:

f = input('enter the file name')
# this line open the file and reads the content f   '.txt' is required
getinfo = open(f  '.txt','r')
content = getinfo.read()
num = content.split("\n") # Splits the content by every new line

print('here are the number in your file',  num)
getinfo.close()

If you need everything in num to be of type int then you can do a for loop to do that like this

f = input('enter the file name')
# this line open the file and reads the content f   '.txt' is required
getinfo = open(f  '.txt','r')
content = getinfo.read()
num = content.split("\n") # Splits the content by every new line

for i in range(len(num)):
   num[i] = int(num[i])

print('here are the number in your file',  num)
getinfo.close()

One thing you need to be careful of, however, is to make sure that your text file doesn't contain any characters instead of numbers, otherwise python will try to convert something like "c" to an integer which will cause an error.

  •  Tags:  
  • Related