简体   繁体   中英

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

I wanted to read a file, but it gave me an error: TypeError: an integer is required (got type str) . It worked a week ago. Changing from "r" to "rt" still gives the error. If i change the "r" to 1 , it gives me this error: AttributeError: 'int' object has no attribute 'readlines'

This is the code:

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()

This is the full Traceback:

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)

In Spyder (my IDE), it gives this error, but executing it throug the command line ( python3 main.py ) works fine.

Well I restarted Spyder and it works so this question is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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