Python create a loop if condition not verified - python

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'

Related

Problem in output regarding taking the file name from user

So I tried to run the code trying to print the lines starting with "How" taking the file name from the user, but the output shows there are 0 lines starting with "How".
content in the file, read.txt-
Hey there, this is Sohail Hassan.
How are you?
How is everything going?
How is everything at college?
fhand = input("enter the file name")
try:
fname = open(fhand)
except:
print("can't open the file")
count = 0
for line in fhand:
if line.startswith("How"):
count = count+1
print("There are,",count,"lines in this file.")
Full corrected version of your code, with a few improvements:
fname = input("enter the file name")
try:
with open(fname, 'w') as fhand:
for line in fhand:
if line.startswith("How"):
count += 1
except:
print("can't open the file '" + fname + "'")
print("There are " + count + " lines starting with 'How' in this file.")

how can i change the file name using Input() function in this code ? any correct form of this code

any correct form of this code
this code form the geeksforgeeks
the code perform correct without
this line "with open("/content/gdrive/My Drive/xyz.exe "wb") as file: "
but how to change this xyz.exe using input() funtion
import requests
file_url = "xyz.exe"
r = requests.get(file_url, stream = False)
file_name = input("Enter your file name")
with open("/content/gdrive/My Drive/"str(file_name)"wb") as file:
for block in r.iter_content(chunk_size = 1024):
if block:
file.write(block)
Python 2.7
new_file_name = raw_input("Enter file name:")
with open("path/to/{}".format(new_file_name), "wb") as f:
Python 3
new_file_name = input("Enter file name:")
with open(f"path/to/{new_file_name}", "wb") as f:

Limit attempt read file only several times

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 ('')

'NameError 'test' not defined. where am I going wrong?

I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.

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.

Categories

Resources