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

1 投票
2 回答
2255 浏览
提问于 2025-04-16 01:35

我有一个Django应用,它会打开一个文件,持续读取这个文件,同时还要往Postgres数据库里写数据。我的问题是,每当我打开文件时,

file = open(filename, 'r')

我就无法在数据库里创建新的内容,

Message.objects.create_message(sys, msg)

本来应该能创建一个包含两个字符串的数据库条目。但是,什么都没有发生,也没有任何错误提示 :( 如果我在写入数据库之前先关闭文件,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)

似乎从文件中读取的字符串和我手动写的字符串之间有区别。有人知道这是为什么吗?

2 个回答

2

你试过使用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()
3

试试这个:

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

撰写回答