0

So far, I've used the range function which works when I simply print the lines imported from the URL but when I try to save them to a txt file it only saves line 5 (or whatever the last number of the range is).

target_url="random URL"
request = requests.get(target_url)
text=request.text
lines=text.split("\n")
for i in range(1, 5):
    savefile = open('c:/Users/ghostsIIV/Desktop/examplefile.txt', 'w')
    savefile.write(lines[i])
savefile.close()
0

1 Answer 1

2

You overwrite your file on every iteration, wiping out the previous information:

for i in range(1, 5):
    savefile = open('c:/Users/ghostsIIV/Desktop/examplefile.txt', 'w')
    savefile.write(lines[i])
savefile.close()

If you want to write five lines, then just leave the file open as you accumulate data:

savefile = open('c:/Users/ghostsIIV/Desktop/examplefile.txt', 'w')
for i in range(1, 5):
    savefile.write(lines[i])
savefile.close()

This is also a good time to learn a (append) mode. Repeat your tutorial on Python files for that information.

Even shorter, open the file and write the four lines you want:

with open('c:/Users/ghostsIIV/Desktop/examplefile.txt', 'w') as savefile:
    savefile.write('\n'.join(lines[1:5])

with closes the file when you exit the block.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.