为什么没有打印我的CSV文件?

2024-06-17 12:42:29 发布

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

我的代码当前将包含类的分数的字典写入CSV文件。这部分由程序正确完成,分数被写入文件,但是写入文件的最新词典没有打印出来。例如,在代码运行一次之后,它将不会被打印,但是一旦代码再次运行,第一位数据将被打印,而新的数据不会被打印。有人能告诉我哪里出错了吗?你知道吗

SortedScores = sorted(Class10x1.items(), key = lambda t: t[0], reverse = True) #this sorts the scores in alphabetical order and by the highest score
FileWriter = csv.writer(open('10x1 Class Score.csv', 'a+'))
FileWriter.writerow(SortedScores) #the sorted scores are written to file     
print "Okay here are your scores!\n"

我猜问题在这里的某个地方,但我不能很准确地指出它是什么或在哪里。我试图通过将文件读回r、r+和rb时改变文件的模式来解决这个问题,但是它们都有相同的结果。你知道吗

ReadFile = csv.reader(open("10x1 Class Score.csv", "r")) #this opens the file using csv.reader in read mode
for row in ReadFile:
    print row
return

Tags: 文件csvthe数据代码inopenthis
2条回答

请记住在操作后关闭文件,否则数据将无法正确保存。你知道吗

尝试使用with关键字,以便Python为您处理闭包:

import csv

with open('10x1 Class Score.csv', 'a+') as f:
    csv_writer = csv.writer(f)
    # write something into the file
    ...
# when the above block is done, file will be automatically closed
# so that the file is saved properly

Input output- python docs

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks: >>> with open('workfile', 'r') as f: ... read_data = f.read() >>> f.closed True File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.

我不知道他们为什么要在文档中这么做,因为这确实很有用,而且是一个非常常见的初学者错误:

SortedScores = sorted(Class10x1.items(), key = lambda t: t[0], reverse = True) #this sorts the scores in alphabetical order and by the highest score
with open('10x1 Class Score.csv', 'a+') as file:
    FileWriter = csv.writer(file)
    FileWriter.writerow(SortedScores) #the sorted scores are written to file     
print "Okay here are your scores!\n"

这将为您关闭文件,即使出现错误,这将防止许多可能的数据丢失

它看起来没有写入文件的原因是,当您执行.write_row()操作时,它不会立即写入硬盘,只会写入缓冲区,缓冲区偶尔会清空到硬盘上的文件中,尽管只有一个write语句,它不需要清空。你知道吗

相关问题 更多 >