简体   繁体   English

将URL文本文件直接下载到CSV文件python

[英]Download URL text file directly to csv file python

I have a link to a text file from US Census and I would like to download it into a directory on my computer. 我有一个来自美国人口普查的文本文件的链接,我想将其下载到计算机上的目录中。

I was thinking about downloading the URL into a text file and then converting the text file into a csv later on. 我当时正在考虑将URL下载到文本文件中,然后再将文本文件转换为csv。 However, I was wondering if it were possible to download directly to a csv file? 但是,我想知道是否可以直接下载到csv文件? If it's possible, would appreciate an example. 如果可能的话,将不胜感激。

This is the link to the data: https://www.census.gov/construction/bps/txt/tb2u2010.txt 这是数据的链接: https : //www.census.gov/construction/bps/txt/tb2u2010.txt

I may be wrong here, but saving that as a .csv file would not be easy. 我在这里可能是错的,但是将其另存为.csv文件并不容易。 I don't know Python very much but I'll leave my two cents here: 我不太了解Python,但我将在这里留下两分钱:

import urllib.request  # lib that handles URLs

target_url = "https://www.census.gov/construction/bps/txt/tb2u2010.txt"

data = urllib.request.urlopen(target_url)

with open('output.txt', 'w') as f:  # change this to .csv
    for line in data:
        f.write(str(data.read()))

This will create a .txt with everything from the website on a single line. 这将创建一个.txt文件,其中包含网站上的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM