目录名称无效

时间:2017-08-17 23:19:12

标签: 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\\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()

我复制的目录会导致桌面上的文本文件。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

关于你想在这里实现什么,这有点模棱两可,但这里有一个快速的例子,说明如何将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)