为什么当我打开一个文本文件时会这样说,“参数应该是整数或无,而不是'str'”

2024-09-30 04:26:48 发布

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

当我存储在note中的文本文件只是一个字符串时,为什么我的代码会说argument should be integer or None, not 'str'。要打开整数便笺,我应该做什么

f = open("testpoem.txt")
# e.g., f = open("data2.txt")
text = f.read("testpoem.txt")
# text is a string that contains the contents of the entire file
    
# problem 1
def string2list(text):
    return text.split()
    
if __name__ == '__main__':
    print(string2list(text))

下面是全部错误

Traceback (most recent call last): File "C:\Users\filetest.py", line 3, in text = f.read("testpoem.txt") TypeError: argument should be integer or None, not 'str'"


Tags: orthetexttxtnonereadnotinteger
1条回答
网友
1楼 · 发布于 2024-09-30 04:26:48

因为read只接受一个参数(size),该参数是“可选的。返回的字节数。默认值为-1,表示整个文件。”

因此,您的代码应该是:

f = open("testpoem.txt", 'r' )
# e.g., f = open("data2.txt")
text = f.read()

相关问题 更多 >

    热门问题