Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无效的目录名_Python_Directory - Fatal编程技术网

Python 无效的目录名

Python 无效的目录名,python,directory,Python,Directory,我收到错误信息: File "C:/Users/AM/PycharmProjects/booyah/first.py", line 5, in main directory = os.chdir(input('Enter the directory of the file you want to read')) NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\AM\\Desktop\\Sa

我收到错误信息:

File "C:/Users/AM/PycharmProjects/booyah/first.py", line 5, in main
directory = os.chdir(input('Enter the directory of the file you want to read'))
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\AM\\Desktop\\Sad.txt'
这是我的密码:

import os

def main():
    answer = input('Would you like to read, write, create, or quit?')
    if(answer == 'read'):
        directory = os.chdir(input('Enter the directory of the file you want to read'))
        w = open(directory, 'r')
        contents = w.read()
        print(contents)
        w.close()
我复制到的目录指向我桌面上的一个文本文件。
谢谢你的帮助

关于您想要在这里实现什么,有点模棱两可,但下面是一个快速示例,说明如何将
read
命令
chdir
解析到指定的目录中,并打印出文件的行

我在本例中硬编码了文件名:

import os

answer = input('Would you like to read, write, create, or quit?: ')
file_name = 'Sad.txt'

if(answer == 'read'):
    directory = os.chdir(input('Enter the directory of the file you want to read: '))

    with open(file_name, 'r') as fh:
        for line in fh.readlines():
            print(line)
…下面是一个非常简短的示例,显示了如果您希望用户发送包含该文件的路径,则如何读取该文件:

import os

answer = input('Would you like to read, write, create, or quit?: ')

if(answer == 'read'):
    file_name = input('Enter the file you want to read: ')

    with open(file_name, 'r') as fh:
        for line in fh.readlines():
            print(line)

代码抛出一个“NotADirectoryError”,您的输入以“Sad.txt”结尾。。。我不认为目录以.txt结尾?一个
目录
并不等于一个
路径
。你提供的是后者。如果需要文件的目录,请调用
os.path.dirname(file\u变量)