简体   繁体   English

如何使用 python 仅将 URL 中的特定文本行保存到 txt 文件?

[英]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.

相关问题 如何将特定文本保存在 .txt 文件中的数组中 - How do I save specific text in an array from .txt file 如何使用 %BASH 将包含特定字符串的行从 a.csv 文件复制到 Python 中的 a.txt 文件? - How do you copy lines that contain specific strings from a .csv file to a .txt file in Python using %BASH? 如何使用beautifulsoup将网站中的文本保存到.txt文件? - How do I save text from website using beautifulsoup to .txt file? 如何从 Python 中的 .txt 文件加载特定行? - How do I load specific rows from a .txt file in Python? 如何使用python从文本文件的行中读取特定字符? - How to read specific characters from lines in a text file using python? 如何从 txt 文件中获取特定列并使用 python 将它们保存到新文件中 - How can I get specific columns form txt file and save them to new file using python 如何将网址内容保存到.txt文件? - How do I save the content of a url to a .txt file? 如何使用Python从包含特定单词的文件中打印行数? - How do I print the number of lines from a File that contains a specific word using Python? 如何使用 Python 解析 txt 文件并从 txt 文件的特定部分创建字典? - How can I parse a txt file and create dictionary from a specific part of the txt file using Python? 如何使用tk使用python 2.7将文本保存到txt文件中 - how to save text into a txt file using python 2.7 using tk
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM