Returning file not found error - python-3.x

I am attempting to read a file called "files.txt" and return each line in order. I receive and catch a no such file or directory when I'm sure the text file is in my working directory. Is there something improper about the code?
def main():
FileRead()
def ReadFile(filename):
files = open(filename)
lines = files.readlines()
for index, line in enumerate(lines):
print(index, "=", line)
def FileRead():
try:
ReadFile("files.txt")
except IOError as e:
print("Could not open file:", e)
if __name__ == "__main__":
main()

Related

os.environ raises keyerror(key) from none

I am making a database gui program and I am experimenting on how to make the .db file in a different folder from the script. I am using python 3.7. Here is the function that I use:
def get_database_file():
dir_path = os.path.join(os.environ[''], 'test_database')
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_path = os.path.join(dir_path, 'test_database.db')
if not os.path.exists(file_path):
try:
conn = sqlite3.connect(file_path)
conn.execute("PRAGMA foreign_keys = 1")
except sqlite3.Error as err:
if conn:
conn.rollback() # reverse any changes before the commit
print("SQLite Error: %s" % err.args[0])
sys.exit(-1)
else:
createDatabase(file_path)
print("Finish database created")
finally:
if conn:
conn.close()
else:
return file_path
if os.stat(file_path) == 0:
print("Empty")
else:
print("Not Empty")
return file_path
When I put os.environ['APPDATA'], this function runs fine without any errors. But when I put os.environ['HOME'], it shows this error message:
Traceback (most recent call last):
File "C:/Users/jojot/PycharmProjects/CreateDatabase/gui_database.py", line 4214, in <module>
database_file = get_database_file()
File "C:/Users/jojot/PycharmProjects/CreateDatabase/gui_database.py", line 4178, in get_database_file
dir_path = os.path.join(os.environ['HOME'], 'test_database')
File "C:\Users\jojot\AppData\Local\Programs\Python\Python37-32\lib\os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'HOME'
I don't understand, what did I do wrong? Please help. Thank you.
It means that you haven't set the environment variable HOME.
If you want the program not to crash if you haven't set that variable you can use:
x = os.environ.get('HOME')
print(x) # None
instead of:
x = os.environ['HOME']
# raise KeyError(key) from None
# KeyError: 'HOME'

using argparse to run a python3 script

I made a function in python3 which takes the path to some txt files and returns a list containing the name of all the txt files.
here is the function:
import os
def files(path):
folder = os.fsencode(path)
filenames = []
for file in os.listdir(folder):
filename = os.fsdecode(file)
if filename.endswith( ('.txt') ):
filenames.append(filename)
filenames.sort()
return filenames
to run this function I can do the following which works perfectly:
if __name__ == "__main__":
path = '/home/final_test'
file_list = files(path)
print(file_list)
but the problem is from this part. I am trying to make a script to run it in command-line using argparse. to do so I added the following code at the end of script but it does not return anything. do you know how to fix it?
def main():
ap = argparse.ArgumentParser(description="")
ap.add_argument('-P', '--path', required=True)
ap.add_argument('-o', '--outlist', required=True)
args = ap.parse_args()
file_list = files(path)
return file_list
if __name__ == "__main__":
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
try:
main()
except IOError as e:
if e.errno != 32:
raise
except KeyboardInterrupt as e:
pass
Your main() function returns None (due to empty return statement). Assuming your files function works OK and file_list get some value, after that line it is no longer used. Probably you want to print within main function file_list or return it to be accessible outside main function (assign it to other variable).
That said I don't see why you need signal lines.
You should print your result(?)
result = main()
print(result)
or
print(main())
Try this:
def main():
ap = argparse.ArgumentParser(description="")
ap.add_argument('-P', '--path', required=True)
#ap.add_argument('-o', '--outlist', required=True)
args = ap.parse_args()
print(args)
file_list = files(args.path)
return file_list
if __name__ == "__main__":
filelist = main()
print(filelist)
I corrected the if __name indenting; I print the return value from main; I set path correctly. And for debugging purposes Iprint(args)`.

CRUD program to read,write and append the details in txt file

It's a school assignment, an event management system. It will write the data to a txt file and retrieve it. Its mostly a CRUD program but not sure why it is not running. It shows space as an error on VS CODE IDE.
It will Create a customer, ask for the seats that he want to book. He can also delete the seats as per ref number before 24 hours.
import random
print("Welcome to the Event System")
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file=open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
invalid syntax (<unknown>, line 41)
I want it to run properly so, I can submit it again.
I haven't checked your whole code, but at least got it running to the point that you could further rectify it:-
import random
print("Welcome to the Event System")
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file = open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
option = int(option)
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
executingmenuinputchoice(menu())
REASON FOR ERRORS:-
Your indentation was all over the place, python language
prioritizes indentation as it uses it to figure out a block span, so you should
keep a consistent indentation scheme throughout your code.
Python uses top down approach for ~interpreting the
program, i.e. It only keeps track of the stuff that it had already
encountered. In your code, the function executingmeninputchoice()
and menu() (the two primary functions used for UI) were stacked
above all other function, therefore when you tried to call other
function from these two function, they aren't called. As the program
doesn't know whether these functions exists or not (as it hasn't
encountered them yet)
A logical error existed in function
executingmenuinputchoice(option) as you were trying to take in
input a string and were comparing it with integer values, and
therefore every time the operation failed and the control got shifted
to the else block, therefore every time you got the same output
'you have chose a wrong option' regardless of whether the input was
legal or not
P.S.:- I haven't tested your full code, as this isn't a code for me service, other logical errors may also exist, so I would recommend you to find and fix those too.

How to handle exception with imap_unordered in python multiprocessing

I am using pool.imap_unordered to apply a function over different txt files saved locally.
Is it possible to capture the exception and pass?
If my code runs into an exception, it blocks the entire loop.
pool = Pool(processes=15)
results = {}
files = glob.glob('{}/10K_files/*.txt'.format(path_input))
for key, output in tqdm(pool.imap_unordered(process_file, files),total=len(files)):
results[key] = output
I've tried something like this:
pool = Pool(processes=15)
results = {}
files = glob.glob('{}/10K_files/*.txt'.format(path_input))
try:
for key, output in tqdm(pool.imap_unordered(process_file, files), total=len(files)):
results[key] = output
except:
print("error")
but then I want to resume the loop from where I started.
Thanks!
You could catch the exception in process_file and return it. Then test for whether the return value is an exception. Here is an example:
import os
import traceback
import multiprocessing as mp
def main():
work_items = [i for i in range(20)]
pool = mp.Pool()
for result in pool.imap_unordered(process_file_exc, work_items):
if isinstance(result, Exception):
print("Got exception: {}".format(result))
else:
print("Got OK result: {}".format(result))
def process_file_exc(work_item):
try:
return process_file(work_item)
except Exception as ex:
return Exception("Err on item {}".format(work_item)
+ os.linesep + traceback.format_exc())
def process_file(work_item):
if work_item == 9:
# this will raise ZeroDivisionError exception
return work_item / 0
return "{} * 2 == {}".format(work_item, work_item * 2)
if __name__ == '__main__':
main()

How do I make my python program to write a new file

I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?
Here is my code:
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2 problems
you should use
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
w+ - create file if it doesn't exist and open it in write mode
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..
https://docs.python.org/2/library/functions.html
2.
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
if sketch.txt file do not exist then "man" and "other" will not initialized
and in the print method will throw another exception
try to run this script
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()

Resources