Skip to content Skip to sidebar Skip to footer

How To Read And Write The .txt File Line By Line In Python?

input.txt - I am Hungry call the shopping mall connected drive I want to read the input.txt line by line and send that as a request to the server and later save the response respe

Solution 1:

To keep it stupid simple, let's implement your broad description of what should happen : ''I want to read the input.txt line by line and send that as a request to the server and later save the response respectively. '' :

for line in readLineByLine('input.txt'):
    sendAsRequest(line)
    saveResponse()

From what I can gather from your question, you already have basically functions sendAsRequest(line) and saveResponse() (maybe under another name), but you miss the function readLineByLine('input.txt'). Here it is:

defreadLineByLine(filename):
    withopen(filename, 'r') as f: #Use with statement to correctly close the file when you read all the lines.for line in f:    # Use implicit iterator over filehandler to minimize memory usedyield line.strip('\n') #Use generator, to minimize memory used, removing trailing carriage return as it is not part of the command.

Solution 2:

Basically you can simply:

withopen('filename') as f:
     for line in f.readlines():
         print line

The output will be:

I am Hungry

call the shopping mall

connected drive

Now for an explanation about the "with" statement you can read here: http://effbot.org/zone/python-with-statement.htm

Post a Comment for "How To Read And Write The .txt File Line By Line In Python?"