AttributeError:模块'os'没有属性'getcwd'?

问题描述 投票:0回答:1

我正在尝试运行一个python程序,该程序会从用户那里获取输入,如目录名,文件名及其内容,然后我尝试在当前路径中使用该文件创建目录,然后将数据写入其中,但是我收到错误消息“ os没有属性mkdir”。

   //Code

     import os

        print(os.getcwd())

        class createfile:
            __name=''
            __file_name=''
            __input_text=''
            def read_and_create(self):
                name = input("Enter the directory name, you want to create: ")
                os.mkdir(self.__name)
                #sdos.mkdir(self.__name)
                self.__file_name=input("Enter the file name, you want to create: ")
                f=open(self.___file_name,'w')
                self.__input_text=input("Enter the text : ")
                f.write(self.__input_text)
                f.close()

            def read_file_content(self):
                x=open(self.__file_name,'r')
                print(x.read())


        o=createfile()
        o.read_and_create()
        o.read_file_content()

这是我使用Pycharm时遇到的错误。

    > "C:\Users\Aryan
    > Kumar\AppData\Local\Programs\Python\Python37-32\python.exe"
    > "C:/Users/Aryan Kumar/Desktop/0/os.py"
    >     Fatal Python error: initsite: Failed to import the site module
    >     Traceback (most recent call last):
    >       File "C:\Users\Aryan Kumar\AppData\Local\Programs\Python\Python37-32\lib\site.py", line 73,
    > in <module>
    >         import os
    >       File "C:\Users\Aryan Kumar\Desktop\0\os.py", line 2, in <module>
    >         print(os.getcwd())
    >     AttributeError: module 'os' has no attribute 'getcwd'
    >     
    >     Process finished with exit code 1


this is the error i got using Spyder ide in anaconda environment

runfile('C:/Users/Aryan Kumar/Desktop/0/untitled0.py', wdir='C:/Users/Aryan Kumar/Desktop/0')
    C:\Users\Aryan Kumar\Desktop\0

    Enter the directory name, you want to create: aac
    Traceback (most recent call last):

      File "<ipython-input-4-fb1c179833e1>", line 1, in <module>
        runfile('C:/Users/Aryan Kumar/Desktop/0/untitled0.py', wdir='C:/Users/Aryan Kumar/Desktop/0')

      File "C:\Users\Aryan Kumar\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 709, in runfile
        execfile(filename, namespace)

      File "C:\Users\Aryan Kumar\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
        exec(compile(f.read(), filename, 'exec'), namespace)

      File "C:/Users/Aryan Kumar/Desktop/0/untitled0.py", line 32, in <module>
        o.read_and_create()

      File "C:/Users/Aryan Kumar/Desktop/0/untitled0.py", line 18, in read_and_create
        os.mkdir(self.__name)

    FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
python-3.7
1个回答
0
投票

这是一个古老的问题,但可能有人遇到相同的问题。我还收到以下错误:AttributeError:模块'os'没有属性'getcwd'。这是因为文件名是os.py。更改文件名后问题已解决。

[还发现在另一个问题中也提供了类似的答案:https://stackoverflow.com/a/43565408/298160

© www.soinside.com 2019 - 2024. All rights reserved.