FileNotFoundError,os.getcwd()返回文件名而不是目录

时间:2017-07-10 13:45:22

标签: python-3.x file-not-found

我有一个尝试读取文件的程序,如果它可以读取文件,它将从该文件生成一个列表,并从该列表中返回一个随机选择给用户。如果找不到该文件,或者有另一个错误消息将提醒用户,程序将默认使用我程序源代码中的默认列表。

我将文件名的第一部分从一个函数传递给readFile()函数,该函数将'.txt'附加到它传递的文件名,并尝试读取三个文件中的一个,具体取决于函数的名称给出。

尽管存在文件,并且我显示了隐藏的扩展名以确保没有调用.txt.txt,程序仍然返回FileNotFoundError

在线搜索,我听说过os.getcwd(),所以我在readFile()函数的开头运行了print(os.getcwd()),返回的是all.txt; “all”是我传递给readFile()以执行此测试的值。

所以我相信文件,在这种情况下无法找到all.txt,因为该函数中程序的工作目录设置为fileName而不是程序目录。

我该如何解决这个问题?

下面是传递文件名的函数,不包括readFile()函数的扩展名;有多个选项,我刚刚包含了第一个提高可读性的选项,所有选项都返回相同的错误,并且行为方式相同。

def generateActivity() :

chores = ['Washing Up', 'Laundry']
fun = ['Watch TV', 'Play a game']

allActivities = chores + fun
print(allActivities)

if menu() == 'R' :

    try :
       allList = readFile('all')
       displayOutput(random.choice(allList))

    except FileNotFoundError :
        print('Sorry, all activities list, file not found')
        print('Using default all activities list...\n')
        displayOutput(random.choice(allActivities))

    except :
        print('Sorry there was an error with all.txt')
        print('Using default all activities list...\n')
        displayOutput(random.choice(allActivities))

这是readFile()函数。

def readFile(list) : 

print(os.getcwd())

READ = 'r'
fileName = list + '.txt'

with open(fileName, READ) as f :
    # Reads the entire file
    dictionary = f.readlines() 

# Seperates each word to create a list of words
Activitylist = [word.strip() for word in dictionary] 

return(ActivityList) 

1 个答案:

答案 0 :(得分:0)

我会使用input()代替def readFile(list)

如果我理解正确,您可以使用以下选项代码:

#!/usr/bin/env python

'''
1. Read a file.
1a. If file can be read, generate a list from that file.
1b. Return a random selection from that list to the user.
'''

'''
2. If file cannot be read or error: alert user with message
2a. Use default list.
'''

import os
import pathlib
import random

#Print the current working directory to check if path is correct.

cwd = os.getcwd()
print("This is the directory the desired file is located: " + cwd)

#Request input from user for name of file. 

file_desired = input() + '.txt'

#Use pathlib to set path of the file. 

path = pathlib.Path('write_full_path_to_directory_here' + file_desired)
print(path)

#If the path of the file exists, use list from file.

if path.is_file():
    with open (file_desired, 'r') as file_wanted:
        print("File is available.")
        dictionary = file_wanted.readlines()
        Activitylist = [word.strip() for word in dictionary]
        print(random.choice(Activitylist))

#If file path does not exist, then use default list.

else:
    print('Sorry, all activities list, file not found')
    print('Using default all activities list...\n')

    chores = ['Washing Up', 'Laundry']
    fun = ['Watch TV', 'Play a game']

    allActivities = chores + fun

    print(random.choice(allActivities))

希望有所帮助!

Omneya