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变量)
。