python - 如何从 txt 文件中获取值到数据库 Django
问题描述
问题摘要:我有一个包含美国所有邮政编码的文件,文件格式为“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 中。)
解决方案
我不确定您的文件夹结构,但我有根据的猜测如下。您正在尝试打开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
所示:
import os
filename = os.path.join(os.path.dirname(__file__), 'zip_codes.txt')