在Python中从txt转换为csv会删除前导零

时间:2019-12-19 21:58:21

标签: python

我正在使用python从网上下载txt文件,并试图将其转换为csv文件。当我将其转换为一个csv文件时,前导零是否已从txt文件中删除?有什么方法可以不删除前导零? txt文件具有一个现场站ID,即“ 000044”,但是如果我将其转换为csv文件以进行进一步的操作,它将变成“ 44”。有解决方法吗?

url = 'http://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/air_temperature/recent/TU_Stundenwerte_Beschreibung_Stationen.txt'
    # Downloads information of all the stations that are available
    urllib.request.urlretrieve(url, "stations.txt")

    product = "stations.txt"
    # Produkt file name is now in product variable
    product = ''.join(product)

    with open('stations.txt', 'r', encoding='ISO-8859-1') as fin:
        data = fin.read().splitlines(True)
    with open('stations.txt', 'w', encoding='ISO-8859-1') as fout:
        fout.writelines(data[2:])

    df = pd.read_fwf(product, header=None)
    # Converts txt file into csv WITHOUT indexing
    df.to_csv('index.csv', index=False)

txt文件:

00003 19500401 20110331            202     50.7827    6.0941 Aachen                                   Nordrhein-Westfalen                                                                               
00044 20070401 20191218             44     52.9336    8.2370 Gro�enkneten                             Niedersachsen      

转换后的csv文件:

0,1,2,3,4,5,6,7
3,19500401,20110331,202,50.7827,6.0941,Aachen,Nordrhein-Westfalen
44,20070401,20191218,44,52.9336,8.237,Gro�enkneten,Niedersachsen

0,1,2是我稍后从frame.rename /

重命名的字段名称

0 个答案:

没有答案
相关问题