在djang中读取文件并写入数据库

2024-10-01 15:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django应用程序,可以打开一个文件,不断地读取它,同时将数据写入Postgres数据库。我的问题是每当我打开一个文件

file = open(filename, 'r')

我无法在数据库中创建新的东西

^{pr2}$

它应该创建一个包含两个字符串的数据库条目。但是,似乎什么都没有发生,并且没有出现任何错误:(如果我决定在写入数据库之前关闭文件file.close(),那么一切都很好。我的问题是我需要打开文件来创建我的对象。有人能解决这个问题吗?谢谢。在

编辑

下面是我的一些代码。基本上,我在一个文件的末尾有以下代码片段,然后在数据库获取信息时将其写入数据库。在

file.seek(0,2)         
while True:
  line = file.readline()
  if not line:
    time.sleep(1)
    continue
  Message.objects.create_message(sys, line)

编辑2

终于成功了,但我不知道为什么。我很想知道这为什么有用:

str1ng = line[0:len(line)-1]
Message.objects.create_message(sys, str1ng)

一些字符串和从中收集的字符串之间的区别文件.readline(). 有什么想法吗?在


Tags: 文件django字符串代码数据库编辑messagereadline
2条回答

试试这个:

file = open(filename, 'r')
fileContents = file.read()
file.close()

你试过linecache吗?像这样的东西可能有用(没有经过测试)。在

import linecache

i = 0
go = True
file = ...
while (go == True):
   out = linecache.getline(file,i)
   ...process out...
   i = i+1
   if i % 100 == 0:
       # check for cache update every 100 lines
       linecache.checkcache(file)
   if ( some eof condition):
       go = False
linecache.clearcache()

相关问题 更多 >

    热门问题