Not sure how or what exceptions should I take into account.
I have the following piece of code that handles default files to pass to the program if not specified.
if len(sys.argv)==1:
fileName = "file1.txt"
else:
fileName = sys.argv[1]
The other part of code is when opening the file:
with open(fileName) as file:
for line in file:
words = line.split(';')
....
....
....
You should use FileNotFoundError.
Example below taking user input:
yourPath = input('Enter your path')
try:
with open(yourPath) as fl:
for i in fl:
print(i)
except FileNotFoundError:
print('Please enter correct path')
OR you can use IOError:
yourPath = input('Enter your path')
try:
with open(yourPath) as fl:
for i in fl:
print(i)
except IOError:
print('Please enter correct path')
OR if you are not sure about just use except:
yourPath = input('Enter your path')
try:
with open(yourPath) as fl:
for i in fl:
print(i)
except:
print('Please enter correct path')
Related
I'm trying to edit text files in real time, like this text box here, you can write and edit any word you want and then save it to the file, think nano for linux. Anyone know a way of doing this?
I have no idea how to start so I haven't tried anything.
Also something simple please doesn't need to be crazy efficient.
The reading and current writing part of the script look like this:
f = open('./PYOS/startMessage.txt', 'r')
start_message = f.read()
print(start_message)
f.close()
while True:
user_input = str(input('P:\> '))
command = user_input.lower()
if command == 'read':
filename = input('Filename: ')
try:
file = open(filename, 'r')
cont = file.read(filename)
print('File contents: ', cont)
except FileNotFoundError:
print('File not found please try again')
elif command == 'write':
filename = input('Filename: ')
try:
file = open(filename, 'w')
write = input('Write in file: ')
cont = file.read(filename)
print('You wrote: ', cont)
except FileNotFoundError:
print('File not found please try again')
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.
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()
I am working on a code in Python 3 with the following prompt:
Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence:0.8475. When you encounter a line that starts with X-DSPAM-Confidence: pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
I have started writing my code (below), but keep getting the following error message from Python:
Traceback (most recent call last):
File "spam_lines_in_file.py", line 14, in <module>
for line in fhand:
NameError: name 'fhand' is not defined
0587388179:ch_07_files juliecruz$
I'm confused because I have defined the variable 'fhand'. Any help from the experts?
count = 0
sum = 0
user = input('Please enter a file name')
try:
fhand = open(user)
except:
print("Not a valid file")
for line in fhand:
line = line.rstrip()
if line.startswith('X-DSPAM-Confidence:'):
print(lines)
count += 1
colon_position = int(line.find(":"))
extract = line[colon_position+1:]
number_extract = float(extract)
sum += number_extract
print("Extracted lines", count)
print("Sum of confidence values", sum)
print("Average of confidence values", sum/count)
Your problem is that fhand is only assigned a value if no exceptions occur.
You wrote:
try:
fhand = open(user)
except:
print("Not a valid file")
So in the case of an exception, fhand is not assigned a value. Which means that when you try to iterate over it, Python throws a NameError as it was never defined.
Maybe what you want is to terminate in the case of an exception? For example:
import sys
try:
fhand = open(user)
except:
print("Not a valid file")
sys.exit()
Or assign a default value to fhand?
import sys
try:
fhand = open(user)
except:
print("Not a valid file")
fhand = 'Default content'
The most likely reason is that, if a error occurs during opening the file, then a warning message is shown "Not a valid file", but processing then continues.
In that case fhand would not be assigned a value, and there would be a NameError
You probably want a loop that repeatedly asks for a filename, and only breaks out when the file has been opened successfully.
while True:
name = input("filename ... ")
try:
fhand = open(name)
except OSerror: # only catch OS errors, not everything.
print("not a valid file")
else:
break
fhand is a file object
try:
fhand = open(user)
except:
print("Not a valid file")
You can not do the following on a file object.
for line in fhand:
You would need to do this:
for line in fhand.readlines():
This isn't a problem for you yet, but it will be soon.
Your real problem is this:
When this code
try:
fhand = open(user)
throws an exception, the fhand variable doesn't get created, so you'd need to exit in the except block.
try:
fhand = open(user)
except:
print("Not a valid file")
sys.exit(1)
There is a mistake in line 11 :) - change to "line"
print(lines)
I'm trying to make function which asks the user for a filename. If the file is not found, it will keep asking. This what I have please help..
def return_text_file(infile):
while infile:
try:
file = open(infile)
except IOError:
print("Could not find the file specified")
infile = input ("Enter the file name")
return open_infile
file_input = input ("Enter the file name")
return_text_file(file_input)
You can create a function (e.g. ask_file_name below) to get a valid answer from the user. It will repeat constantly until an existing name is given.
import os
path_str = '/home/userblabla/ProjectBlabla/'
def ask_file_name():
files_detected = os.listdir(path_str)
while True:
print('\nFiles:')
for file in files_detected:
print(file)
file_name_given = input('\nFile name?')
if file_name_given not in files_detected:
print("Could not find the file specified")
else:
print('Thanks friend.')
return file_name_given
my_file_name = ask_file_name()
with open(my_file_name, 'r') as opened_file:
# Do stuff on opened_file
......
with open() automatically closes the file, and it might be better if you use it instead of open().