简体   繁体   English

写入文件f后,调用f.read()返回None

[英]After writing to file f, calling f.read() returns None

The problem is that after writing to file it's empty, I dont understand why. 问题是写入文件后它是空的,我不明白为什么。 here is my code: 这是我的代码:

    self.f = tempfile.NamedTemporaryFile(delete=False)    
    for i in range(self.num_chars_file):
        self.f.write(str(i))
    reader_writer.testfile = self.f.name
    print '************************'
    print self.f.read()

why does this happen, and how to correct this ? 为什么会发生这种情况,以及如何纠正这种情况?

You should move the file position to the beginning. 您应该将文件位置移到开头。

print '************************'
self.f.seek(0) # <--------
print self.f.read()

Otherwise, the file position is at the end of the file (where the file write was done) 否则,文件位置在文件末尾(完成文件写入的位置)

You need to seek back to the start if you want to read the same data back again: 如果要再次读回相同的数据,则需要重新开始:

self.f.seek(0)
print self.f.read()

File objects are linear, like a tape, and have a 'current position'. 文件对象是线性的,就像磁带一样,并且具有“当前位置”。 When you write to a file, the current position moves along, so that new writes take place at that position, moving the position onwards again. 当您写入文件时,当前位置会随之移动,以便在该位置进行新的写入,并再次向前移动该位置。 The same applies to reading. 阅读同样如此。

So, after writing, the file position is right at the end of the file. 因此,写入后,文件位置就在文件末尾。 Trying to read without moving the file position means no more data will be found. 尝试在不移动文件位置的情况下进行读取意味着将找不到更多数据。 file.seek() moves the current file position elsewhere; file.seek()将当前文件位置移动到其他位置; file.seek(0) moves it back to the start of the file. file.seek(0)将其移回到文件的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM