简体   繁体   English

file.open无法按照我认为的方式工作

[英]file.open does not work the way I thought it should

My code is this: 我的代码是这样的:

self.data = open("/myData", "a")
self.data.close()

self.data = open ("myData", "r")


    self.master = Tk()       
    if (self.data.read()is not None):
        print 2
        print self.data.readlines()
        print 1

I usually get an empty print between the 2 and the one. 我通常在2和1之间得到空白打印。

I do know for certain that there is something written in myData. 我确实知道myData中写了一些东西。 I have tried other methods of opening myData, such as 我尝试了其他打开myData的方法,例如

self.data = open ("/myData", "r")

which gives me "permission denied" (yes, I do have reading and writing rights on that file, I checked that) 这使我“权限被拒绝”(是的,我确实对该文件具有读写权限,因此我检查了该权限)

and

self.data = open ("/game-engineering/myData", "r")

which gives me "file not found". 这给了我“找不到文件”。

Am I making some stupid path mistake? 我在犯一些愚蠢的路径错误吗? I do know for certain that the file is not empty, I see what is in there if I open it by hand. 我确实知道该文件不是空的,如果手动打开它,我会看到其中的内容。

When you call read , you "consume" the file (the cursor moves to the end of the file) - So when readlines is called it immediately hits the EOF and such returns an empty list. 当您调用read ,您将“消耗”该文件(光标移至文件末尾)-因此,当调用readlines时,它将立即命中EOF,从而返回一个空列表。

In most cases (with readlines) you can just use it directly, because if the file is empty you'll get an empty list, so you'll never enter the iteration anyway. 在大多数情况下(带有读取行),您可以直接使用它,因为如果文件为空,您将得到一个空列表,因此无论如何您都永远不会输入迭代。

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

相关问题 当我打开要首先写入的文件时,为什么在File.open中无法读取任何内容? - Why I can't read anything with File.open in python when I open the file to write first? Tkinter Label 不像我想象的那样工作 - Tkinter Label doesn't work as I thought it does Django STATIC_FILE无法按照我的想法工作? - Django STATIC_FILE doesn't work as i thought? 用“ w”打开file.open不会在Python tKinter按钮方法中覆盖文件 - file.open with “w” not overwriting file in Python tKinter button method Azure Function Python - 使用 file.open 时没有这样的文件或目录 - Azure Function Python - No such file or directory when using file.open 在setup.py中找不到File.open(自述文件) - File.open(readme) in setup.py isn't found with file.open('r',encoding="utf-8") as f: AttributeError: 'str' object has no attribute 'open' - with file.open('r',encoding="utf-8") as f: AttributeError: 'str' object has no attribute 'open' 为什么我没有像我想的那样改变全局范围 - Why am I not changing the global scope the way I thought 为什么当我打开一个文本文件时会这样说,“参数应该是整数或无,而不是‘str’” - Why does it say this when I open a text file, "argument should be integer or None, not 'str'" 我应该在函数外部还是内部打开文件? - Should I open a file outside or inside a function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM