繁体   English   中英

类型错误:在 Python 中打开文件时需要 integer(获取类型 str)

[英]TypeError: an integer is required (got type str) when opening file in Python

我想读取一个文件,但它给了我一个错误: TypeError: an integer is required (got type str) 它在一周前工作。 "r"更改为"rt"仍然会出现错误。 如果我将"r"更改为1 ,它会给我这个错误: AttributeError: 'int' object has no attribute 'readlines'

这是代码:

from time import sleep
def getText():
    file = open("data.txt", "r")
    text = file.readlines()
    file.close()
    return text

def checkText():
    while True:
        sleep(5)
        parseText(getText())

def parseText(text):
    print(text)

checkText()

这是完整的追溯:

Traceback (most recent call last):

  File "<ipython-input-40-1a63410aad11>", line 1, in <module>
    runfile('/home/whitespace/coding/python/scripts/main.py', wdir='/home/whitespace/coding/python/scripts')

  File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/whitespace/coding/python/scripts/main.py", line 19, in <module>
    checkText()

  File /home/whitespace/coding/python/scripts/main.py", line 14, in checkText
    parseText(getText())

  File "/home/whitespace/coding/python/scripts/main.py", line 6, in getText
    file = open("data.txt", "r")

TypeError: an integer is required (got type str)

在 Spyder(我的 IDE)中,它给出了这个错误,但是通过命令行( python3 main.py )执行它可以正常工作。

好吧,我重新启动了 Spyder 并且它工作正常,所以这个问题完成了。

暂无
暂无

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

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