【问题标题】:How to get values from a txt file into a database Django如何从 txt 文件中获取值到数据库 Django
【发布时间】:2019-01-15 04:35:33
【问题描述】:

problem 总结:我有一个包含美国所有邮政编码的文件,文件格式为“ZIP,LATITUDE,LONGITUDE\n' 我想将每一行保存为以下的模型实例:

class ZipCode(models.Model):
    zip_code = models.CharField(max_length=7)
    latitude = models.DecimalField(decimal_places=6, max_digits =12)
    longitude = models.DecimalField(decimal_places=6, max_digits =12)

无需手动手动输入每一个,因为这将花费很长时间。

我的解决方案尝试: 编写一个视图来处理这个一次性任务似乎不是最好的方法,但这是我能想到的,所以我尝试了以下方法:

def update_zipcodes(request):
    zip_code_file = open('zip_codes.txt')

    #lists to hold zip code, longitude and latitude values:
    zip_codes = []
    latitude = []
    longitude = []

    for line in zip_code_file.readlines():
        #example line "00601,18.180555, -66.749961"
        zipcode, lat, lng = line.strip().split(',')
        zip_codes.append(zipcode)
        latitude.append(lat)
        longitude.append(lng)

    #convert lat and long to floats
    latitude = [float(i) for i in latitude]
    longitude = [float(i) for i in longitude]

    counter = 0
    for item in zip_codes:
        zip_code_object = ZipCode(zip_code=zip_codes[counter],latitude=latitude[counter],longitude=longitude[counter])
        zip_code_object.save()
        counter= counter+1

    return HttpResponse('working')

它返回了cannot find file 'zip_codes.txt',即使我将此文件放在与视图相同的文件夹中。显然我不知道如何实现手头的目标。无论如何要连接到我的数据库并按指定上传值吗? (原始值可以在https://gist.githubusercontent.com/erichurst/7882666/raw/5bdc46db47d9515269ab12ed6fb2850377fd869e/US%2520Zip%2520Codes%2520from%25202013%2520Government%2520Data 看到,我复制并粘贴到 zip_codes.txt)

【问题讨论】:

    标签: python database python-3.x sqlite django-models


    【解决方案1】:

    我不确定您的文件夹结构,但我有根据的猜测如下。您正在尝试打开zip_codes.txt,这是一个相对路径,而不是绝对路径。绝对路径从根目录开始。在 Linux 系统中,这可能看起来像 /path/to/file/zip_codes.txt,而在 Windows 系统中,它可能看起来像 C:\path\to\file\zip_codes.txt。无论如何,在 Python 中你都可以使用。但是,使用相对路径时必须小心。如果您基于相对路径搜索文件,Python 将仅在 当前工作目录 中查找。因此,您需要指定从当前工作目录到文件存储位置的相对路径。例如,如果您有以下数据结构:

    project
      /folder
        view.py
        zip_codes.txt
    

    如果您运行python project/view.py(当前工作目录为/project),其中view.py 是您上面的文件,使用open('zip_codes.txt'),Python 将无法找到该文件,因为它不在当前目录中工作目录。如果你知道的话,你可以写出完整的路径,例如open('folder/zip_codes.txt')。您还可以将工作目录更改为folder 目录,然后直接从那里运行python view.py。在这种情况下,程序将能够找到该文件,因为它位于同一工作目录中。

    另一个解决方法是,如果您仍想从与以前相同的工作目录运行程序,您可以使用os 模块,如this post 所示:

    import os
    
    filename = os.path.join(os.path.dirname(__file__), 'zip_codes.txt')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 2014-07-20
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多