简体   繁体   中英

Read each line of a text file and then split each line by spaces in python

I am having a silly issue whereby I have a text file with user inputs structured as follows:

x = variable1
y = variable2

and so on. I want to grab the variables, to do this I was going to just import the text file and then grab out the UserInputs[2], UserInputs[5] etc. I have spent a lot of time reading through how to do this and the closest I got was initially with the csv package but this resulted in just getting the '=' signs when I printed it so I went back to just using the open command and readlines and then trying to iterate through the lines and splitting by ' '.

So far I have the following code:

Text_File_Import = open('USER_INPUTS.txt', 'r')
Text_lines = Text_File_Import.readlines()

for line in Text_lines:
    User_Inputs = line.split(' ')

print User_Inputs

However this only outputs the first line from my text file (ie I get 'x', '=', 'variable1'but it never enters the next line. How would I iterate this code through the imported text file?

I have bodged it a bit for the time being and rearranged the text file to be variable1 = x and so on. This way I can still import the variable and the x has the /n after it if I just import them with the folloing code:

def ReadTextFile(textfilename):

    Text_File_Import = open(textfilename, 'r')
    Text_lines = Text_File_Import.readlines()

    User_Inputs = Text_lines[1].split(' ')
    User_Inputs_clength = User_Inputs[0]

    #print User_Inputs[2] + User_Inputs_clength

    User_Inputs = Text_lines[2].split(' ')
    User_Inputs_cradius = User_Inputs[0]

    #print User_Inputs[2], ' ', User_Inputs_cradius

    return User_Inputs_clength, User_Inputs_cradius

Thanks

You have a lot in indentation issues. To read lines and split by space the below snippet should help.

Demo

with open('USER_INPUTS.txt', 'r') as infile:
    data = infile.readlines()
    for i in data:
        print(i.split())

I don't quite understand the question. If you want to store the variables: As long as the variables in the text file are valid python syntax (eg. strings surrounded by parentheses) , here is an easy but slightly insecure method:

file=open('file.txt')
exec(file.read())

It will store all the variables, with their names.

If you want to split a text file between the spaces:

file=open('file.txt')
output=file.read().split(' ')

And if you want to replace newlines with spaces:

file=open('file.txt')
output=file.read().replace('\n', ' ')

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