Limit attempt read file only several times - python

I want to make a limit (say three times) to the attempts when trying to open file and the file cannot be found.
while True:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
except FileNotFoundError:
print ('File does not exist')
print ('')
else:
break
The result of the code above, there is no limit. How can I put the limit in the above codes.
I am using python 3.5.

Replace while True: by for _ in range(3):
_ is a variable name (could by i as well). By convention this name means you are deliberately not using this variable in the code below. It is a "throwaway" variable.
range (xrange in python 2.7+) is a sequence object that generates (lazily) a sequence between 0 and the number given as argument.

Loop three times over a range breaking if you successfully open the file:
for _ in range(3):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
break
except FileNotFoundError:
print ('File does not exist')
print ('')
Or put it in a function:
def try_open(tries):
for _ in range(tries):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename, "r", newline='')
return inputfile
except FileNotFoundError:
print('File does not exist')
print('')
return False
f = try_open(3)
if f:
with f:
for line in f:
print(line)

If you want to use a while loop then the following code works.
count = 0
while count < 3:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
count += 1
except FileNotFoundError:
print ('File does not exist')
print ('')

Related

NameError for filename?

I'm trying to write a program that assigns prices to a list, but I'm having trouble. I keep getting a NameError, that costlist is not defined. The program should ask for an input, append it to the list, and go through the whole list, then write it to the .txt file.
import os
def main():
if os.path.exists("costlist.txt"):
os.remove("costlist.txt")
print ("Assignment 6")
print ()
filename = input("Enter a file name, please. Or enter end to end.")
while filename != "end":
try:
file = open(filename, "r")
listie = file.readlines()
for item in listie:
print(item)
break
except FileNotFoundError:
filename = input("Sorry, that file wasn't found. Try again?")
if filename == "end":
exit
file.close()
listie.sort()
file = open(filename, "w")
for item in listie:
file.write(item.strip("\n"))
file.close()
for item in listie:
cost = input(print( item + "should cost how much?"))
try:
float.cost
except ValueError:
print ("You entered an invalid float that can't convert string to float:" + cost)
print ("Skipping to the next item after" + item)
print (item + "has a cost of" + cost + "dollars")
file = open(costlist.txt, "a")
file.append(cost)
print ("Cost List")
file = open (costlist.txt, "r")
for item in file:
print (item)
print ("Program End")
You forgot to enclose the file name by quotes.
Change file = open(costlist.txt, "a") to file = open("costlist.txt", "a")
And
file = open (costlist.txt, "r") to file = open ("costlist.txt", "r")

Error being written to file when trying to write output

In this spellchecking program i created i seem to be getting a error when trying to write to the output file.The file is created but instead of the output being written an error " <_io.TextIOWrapper name='f.txt' mode='w' encoding='cp1252'>name " is.
I've tried looking for solutions.
print('Spell checking program for Exam 3 lab')
inputFile = input('Enter the name of the file to input from: ')
outputFile = input('Enter the name of the file to output to: ')
f = open("linuxwords.txt", "r")
sent = open(inputFile+ '.txt', "r")
butt = open(outputFile+'.txt', 'w')
word = sent.readline()
print ("mispelled words are:")
while word:
word = word.lower()
success = False
x = word.split()
y=len(x)
for i in x:
success = False
f = open("linuxwords.txt", "r")
line = f.readline()
while line:
if i == line.strip():
success = True
break
line = f.readline()
f.close()
if success == False:
print (i)
word = sent.readline()
with open(outputFile+'.txt', 'w') as f:
f.write(str(butt))
f.write(i)
try:
'''''''
I'm sure my mistake is here, idk
'''''''
f = open(outputFile, "w")
f.write(i)
except:
print('The file',outputFile, 'did not open.')
sent.close()
''''''
Result below
''''''''
Spell checking program for Exam 3 lab
Enter the name of the file to input from: spw
Enter the name of the file to output to: f
misspelled words are:
deks
chris
delatorre
huis
lst
f = open(outputFile)
f.write(i)
You're opening the file for reading, and then trying to write to it.

how to create an exact copy of a non-text binary file in python

The program should copy the content of in_file_name to the out_file_name. This is what I have but it keeps crashing.
in_file_name = input('Enter an existing file: ')
out_file_name = input('Enter a new destination file: ')
try:
in_file = open(in_file_name, 'r')
except:
print('Cannot open file' + ' ' + in_file_name)
quit()
size = 0
result = in_file.read(100)
while result!= '':
size += len(result)
result = in_file.read(100)
print(size)
in_file.close()
try:
out_file = open(out_file_name, 'a')
except:
print('Cannot open file' + ' ' + out_file_name)
quit()
out_file.close()
You can use shutil for this purpose
from shutil import copyfile
in_file_name = input('Enter an existing file: ')
out_file_name = input('Enter a new destination file: ')
try:
copyfile(in_file_name, out_file_name)
except IOError:
print("Seems destination is not writable")
There's 2 things:
There's better ways to do this (like using shutil.copy and various other functions in the standard library to copy files)
If it's a binary file, open it in "binary" mode.
Anyway, here's how to do it if you're sticking to manually doing it.
orig_file = "first.dat"
copy_file = "second.dat"
with open(orig_file, "rb") as f1:
with open(copy_file, "wb") as f2:
# Copy byte by byte
byte = f1.read(1)
while byte != "":
f2.write(byte)
byte = f1.read(1)
Using std library functions: How do I copy a file in python?
Here is what I did. Using while ch != "": gave me a hanging loop, but it did copy the image. The call to read returns a falsy value at EOF.
from sys import argv
donor = argv[1]
recipient = argv[2]
# read from donor and write into recipient
# with statement ends, file gets closed
with open(donor, "rb") as fp_in:
with open(recipient, "wb") as fp_out:
ch = fp_in.read(1)
while ch:
fp_out.write(ch)
ch = fp_in.read(1)

inputting a words.txt file python 3

I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.

Python create a loop if condition not verified

I'm using python 2.6.6 and I can't solve my problem.
I have this code:
file = raw_input('Enter the name of the file: ')
try:
text_file = open(file,'r')
except IOError:
print 'File not found'
file = raw_input('Enter the name of the file: ')
text_file = open(file,'r')
How can i turn this into a loop so that if the user inputs a wrong file name or file its not in that location it continues asking for the file?
Regards,
Favolas
while True:
file = raw_input('Enter the name of the file: ')
try:
text_file = open(file,'r')
break
except IOError:
print 'File not found'

Categories

Resources