打开文件

时间:2019-06-23 14:16:48

标签: python python-3.x windows file

我想编写一个控制台程序,该程序从文件(.txt)中读取内容。 但是,从菜单中选择“ 2”(从文件加载)后,我遇到了问题。我收到一个我无法处理的错误。

def open(args):
    path = 'C:/Users/Tom/Desktop/python/crc/crc2/demofile.txt'
    plik = open(path,'r')
    content = plik.read()
    print(content)

def menu(args):
    print("MENU \n")
    print("1: Ciąg CRC podany z klawiatury \n2: Ciąg CRC wczytany z pliku")

    m = input()
    arg2 = 0
    if m=='1':
        cal(args)
    elif m =='2':
        open(args)
    else:
        print("Podaj poprawną wartość !!!")
        menu(args)
    return 0

错误:

Exception has occurred: TypeError
open() takes 1 positional argument but 2 were given
  File "C:\Users\Tom\Desktop\python\crc\crc2\crc.py", line 8, in open
    plik = open(path,'r')
  File "C:\Users\Tom\Desktop\python\crc\crc2\crc.py", line 37, in menu
    open(args)
  File "C:\Users\Tom\Desktop\python\crc\crc2\crc.py", line 48, in main
    menu(args)
  File "C:\Users\Tom\Desktop\python\crc\crc2\crc.py", line 55, in <module>
    sys.exit(main(sys.argv))

1 个答案:

答案 0 :(得分:0)

这是因为您重新定义了open,所以调用open就像调用您的自定义函数。相反,请导入builtins模块以避免名称修改:

import builtins

def open(args):
    path = 'C:/Users/Tom/Desktop/python/crc/crc2/demofile.txt'
    plik = builtins.open(path,'r') # Calling the built-in open instead of your function
    content = plik.read()
    print(content)

def menu(args):
    print("MENU \n")
    print("1: Ciąg CRC podany z klawiatury \n2: Ciąg CRC wczytany z pliku")

    m = input()
    arg2 = 0
    if m=='1':
        cal(args)
    elif m =='2':
        open(args)
    else:
        print("Podaj poprawną wartość !!!")
        menu(args)
    return 0