简体   繁体   中英

How to read variables line by line from text file?

Updated based on comments

I have a txt file that has a list of variables (delimiter can be anything - I am using comma for illustration)

URL, filename, folder
URL, filename, folder  
URL, filename, folder

I have some code that processes the variables URL, filename and folder and writes to a database. I want to loop through each line and process the variables as I go. So for example

read variables URL, filename, folder in first line 
process
read variables URL, filename, folder in second line 
process
etc

There seems to be plenty of examples to read and display the line items in a txt file, but I am struggling to find an example that reads a line, processes some code using those variables in the line, and then looping to the next line.

Updated with code based on answer below

with open(r"F:\Python\test.txt", "r") as inputfile:
for line in inputfile:
    URL, filename, folder = line.rstrip('\n').split(',')
 <rest of code>

Script runs using variables from line 1 of the text file but does not loop to line 2 and process the second (or third etc) set of variables.

If we assume the structure you put forth for each line: URL, filename, folder , you can grab all 3 variables in one go as such:

with open('my_file.txt', 'r') as inputfile:
    for line in inputfile:
        url, filename, folder = line.rstrip('\n').split(', ')
        db.insert(url, filename, folder) # Or other command as needed

Note that you are splitting on a comma plus a space with line.split(', ') , as your input file separates fields with a comma plus a space. If it is truly just comma-delimited, you can take the space out of the split function call.

First I'm going to assume that what you mean by "variables" is the text inside the file, separated by commas. if that's the case then this should work:

with open('file_name.txt', 'r') as file:
    for line in file:
        for item in line.split(','):
            # do something with each item here

keep in mind that the items will be strings

UPDATED to reflect the change in your example file

Thanks for everybodies assistance. Based on Sam and Tim codes I resolved the problem

def code():

with open(r"F:\Python\test.txt", "r") as inputfile:
    for line in inputfile:
        URL, filename, folder = line.rstrip('\n').split(',')
        code()

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