Home > Software engineering >  How to call elements from a .txt file with python?
How to call elements from a .txt file with python?

Time:11-16

I have a .txt file that was saved with python. It has the form:

file_inputs

Where the first line is just a title that helps me remember the order of each element that was saved and the second line is a sequence of a string ('eos') and other elements inside. How can I call the elements so that inputs[0] returns a string ('eos') and inputs[1] returns the number "5", for example?

CodePudding user response:

I am not sure why you want inputs[&] to return 5.

However here is a the standard (simple) way to read a text file with python:

f = open('/path/to/file.txt', 'r')
content = f. read()
#do whatever you want there
f. close()

To get eos printed first you might want to iterate through the content string until you find a space. For the 5 idk.

CodePudding user response:

if i could understand, you will have to do something like this

input = open(<file_name>, 'r')
input = input.readlines()
input.pop(0) #to remove the title str
#now you can have an array in wich line of .txt file is a str
new_input = [None]*len(input)
for index, line in enumerate(input):
  new_input[index] = line.split(",") #with this your input should be an array of arrays in wich element is a line of your .txt with all your elements
#in the end you should be able to call
input[0][1] #first line second element if i didnt mess up this should be 5
  • Related