[英]How do I save only specific lines of text from a URL to a txt file using python?
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).到目前为止,我已经使用了 function 范围,当我简单地打印从 URL 导入的行但当我尝试将它们保存到 txt 文件时,它只保存第 5 行(或范围的最后一个数字)。
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()
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.这也是学习(附加)模式a
好时机。 Repeat your tutorial on Python files for that information.重复有关 Python 文件的教程以获取该信息。
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. with
退出块时关闭文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.