2017-07-10 2 views
0

私はファイルを読み込もうとするプログラムを持っています。ファイルを読むことができれば、そのファイルからリストを生成し、そのリストからランダムな選択を返します。ユーザー。ファイルが見つからない場合、または別のエラーが発生した場合、メッセージはユーザに警告し、プログラムはデフォルトで自分のプログラムのソースコード内のデフォルトリストを使用します。FileNotFoundError、os.getcwd()はディレクトリではないファイル名を返します

ファイル名の最初の部分をある関数からreadFile()関数に渡します。この関数は渡されたファイル名に '.txt'を追加し、関数名に応じて3つのファイルのいずれかを読み込もうとします与えられた。既存のファイルにもかかわらず

、と私は確信して.txt.txtが呼び出されなかっ作るために隠された拡張子を表示しましたが、プログラムはまだ私はos.getcwdの言及を聞いた、オンライン検索FileNotFoundError

を返します()ので、私はreadFile()関数の先頭にprint(os.getcwd())を実行し、返されたのはall.txtでした。 "all"は、このテストを実行するためにreadFile()に渡した値です。

この関数内のプログラムの作業ディレクトリがプログラムディレクトリではなくfileNameに設定されているので、この場合all.txtは見つかりません。

どうすればこの問題を解決できますか?

以下は、拡張子を含まないファイル名をreadFile()関数に渡す関数です。複数のオプションがあります。ここでは読みやすさを向上させるための最初のオプションを追加しました。すべてのオプションは同じエラーを返し、同じように動作します。

これは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) 

答えて

0

私の代わりにdef readFile(list)input()使用します。助け

#!/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)) 

希望:

は、ここで私が正しくあなたを理解している場合、使用するために、オプションのコードです!

オムニバ

+0

@Omneya – sugarfree

関連する問題