python: check file extension and prompt again input if invalid file extension - python

problem
Doing a while loop to validate file extension. If a file extension is not .exe or .bat, ask user input again. I am looking for a solution without using import endswith break functions.
code
format = " "
while file[:-4] != ".bat" and file[:-4] != ".exe":
format = input("Enter file you like to open: ")
if format[:-4] == ".bat" or format[:-4] == ".exe":
callFunction(format)
else:
file = input("Enter file you like to open: ")

To follow Asking the user for input until they give a valid response and using os.path.splitext() to extract the file extension:
import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
while True:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
if extension in ALLOWED_EXTENSTIONS:
break
with open(filename) as f:
# do smth with f
Without break:
import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
extension = None
while extension not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
with open(filename) as f:
# do smth with f
Without break and without any imports:
ALLOWED_EXTENSTIONS = (".bat", ".exe")
filename = ""
while not filename.endswith(ALLOWED_EXTENSTIONS):
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f
Without break and without any imports and without endswith():
ALLOWED_EXTENSTIONS = {"bat", "exe"}
filename = ""
while filename.rsplit(".",1)[-1] not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f

You don't need a loop
def ask_exe(prompt='Executable file name? '):
name = input(prompt)
if name[-4:] in {'.exe', '.bat'}: return name
return ask_exe(prompt='The name has to end in ".exe" or ".bat", please retry: ')
[no breaks, no imports, almost no code...]
As noted by ShadowRanger my code, that uses set notation for the membership test, is suboptimal for Python versions prior to 3.2. For these older versions using a tuple avoids computing the set at runtime, each and every time the function is executed.
...
# for python < 3.2
if name[-4:] in ('.exe', '.bat'): return name
...

Related

How to find a certain string/name in a txt file?

So im making a name generator/finder, So for the find command i want to find that name in the txt file with the line number! So how do i find the name with the line number?
line = 0
names = open(r"names.txt", "r")
name1 = names.readlines()
uname = input("Please enter the name you want to find: ")
for name in name1:
try:
print(name)
print(line)
if name == uname:
print(f"Found name: {name} \nLine No. {line + 1}")
else:
line = line + 1
except:
print("Unable to process")
But it seems to not work except if you write the last name in file it works. So could give any help?
EDIT: Ive found a way so you can reply if you want to for further people running into the problem!
Try this:
with open("names.txt", "r") as f:
file_contents = names.read().splitlines()
uname = input("Please enter the name you want to find: ")
for line, row in enumerate(file_contents):
if uname in row:
print('Name "{0}" found in line {1}'.format(uname, line))
Yo
if "namefilled" in name :
print("found it")
You can use pathlib if you have Python 3.4+. Pretty handy library.
Also, context management is useful.
# Using pathlib
from pathlib import Path
# https://docs.python.org/3/library/fnmatch.html?highlight=fnmatch#module-fnmatch
import fnmatch
# Create Path() instance with path to text file (can be reference)
txt_file = Path(r"names.txt")
# Gather input
uname = input("Please enter the name you want to find: ")
# Set initial line variable
line = 0
find_all = False
# Use context maangement to auto-close file once complete.
with txt_file.open() as f:
for line in f.readlines():
# If python 3.8, you can use assignment operator (:=)
if match_list := fnmatch.filter(line, uname) is not None: # Doe not match substring.
number_of_names = len(match_list)
name_index = [i for i, element in enumerate(line.split()) for word in match_list if word == element]
print(f"""
{number_of_names} name{"s" if number_of_names > 0 else ""} found on line {line} at position {name_index}.
""".strip())
line += 1
Edited to include fnmatch per some other comments in this thread about matching the full string vs. a substring.
You could try something like this:
import re
search_name = input("Enter the name to find: ")
with open("names.txt", "r") as f:
for line, row in enumerate(f.read().splitlines()):
if re.findall('\\b'+search_name+'\\b', row, flags=re.IGNORECASE):
print('Name "{0}" found in line {1}'.format(search_name, line))
You can remove the flags=re.IGNORECASE flag in case you want the seaarch to be case-sensetive.

How can I open and read an input file and print it to an output file in Python?

So how can I ask the user to provide me with an input file and an output file?
I want the content inside the input file provided by the user to print into the output file the user provided. In this case, the user would put in this
Enter the input file name: copyFrom.txt
Enter the output file name: copyTo.txt
inside the input file is just the text "hello world".
Thanks. Please keep it as simple as you can if possible
If you just want to copy the file, shutil’s copy file does the loop implicitly:
import os
from shutil import copyfile
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
copyfile(openfile, outputfile)
This this post How do I copy a file in Python? for more detail
Here is an example that should work in Python3. The input and output file names would need to include the full path (i.e. "/foo/bar/file.txt"
import os
input_file = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')
def update_file(input_file, output_file):
try:
if os.path.exists(input_file):
input_fh = open(input_file, 'r')
contents = input_fh.readlines()
input_fh.close()
line_length = len(contents)
delim = ''
if line_length >= 1:
formatted_contents = delim.join(contents)
output_fh = open(output_file, 'w')
output_fh.write(formatted_contents)
output_fh.close()
print('Update operation completed successfully')
except IOError:
print(f'error occurred trying to read the file {input_fh}')
update_file(input_file, output_file)
You can do this...
import os
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
if os.path.isfile(openfile):
file = open(openfile,'r')
output = open(outputfile,'w+')
output.write(file.read())
print('File written')
exit()
print('Origin file does not exists.')
To input the input-file and output-file names, simply use the input(s) function where s is the input message.
To get the "content inside the input file provided by the user to print into the output file," that would mean reading the input file and writing the read data into the output file.
To read the input file, use f = open(input_filename, 'r'), where the first argument is the filename and the second argument is the open mode where 'r' means read. Then letting readtext be the read text information of the input file, use readtext = f.read(): this returns the entire text content of f.
To output the read content to the output file, use g = open(output_filename, 'w'), noting that now the second argument is 'w', meaning write. To write the data, use g.write(readtext).
Please note that an exception will be raised if the input file is not found or the output file is invalid or not possible as of now. To handle these exceptions, use a try-except block.
This is effectively a file-copying operation in Python. shutil can serve as a useful alternative.
First you have to read the file and save it to some variable (here rd_data):
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
Then you have to write the variable to other file:
f = open(output_file_name,"w")
f.write(rd_data)
f.close()
The full code is given below:
import os
input_file_name = input("Enter file name to read: ")
output_file_name = input("Enter file name to write: ")
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
f = open(output_file_name,"w")
f.write(rd_data)
f.close()

How to have the option of using sys.arg or raw_input as ways of importing files on python?

Currently I have a short program which can take two different files on the command line as so: $python myscript.py file1 file2
This is through using the sys.arg function, as in:
with open(sys.argv[1], 'r') as a, open(sys.argv[2], 'r') as b:
while True:
try:
#code does stuff for file1
while True:
try:
#code does stuff for file2
The other way of importing the files is by asking the user to input the file names as so:
while True:
userin = raw_input("Options (1, 2 or 3): ")
if userin == '1':
fileopen = raw_input("Enter file name: ")
#etc etc
However, I would like to combine these- so that I can either specify the two files on the command line along with the program- or just open the program and then specify the files. How might I go about this?
Thanks
Why not simply use an if-statement. For example:
if len(sys.argv) >= 3:
filename1 = sys.argv[1]
filename2 = sys.argv[2]
else:
filename1 = raw_input("Enter filename 1")
filename2 = raw_input("Enter filename 2")
Or, if you don't want to write code twice:
def getFilename(position):
if position < len(sys.argv): # Filename not given as argument
return sys.argv[position]
else:
return raw_input("Enter filename of file number {}".format(position))
filename1 = getFilename(1)
filename2 = getFilename(2)
However, if you plan on adding more command line arguments in the future, using argparse would probably be a good idea.

Cannot read Excel chart properly with intended line of code

So this might be a simple solution but I can't seem to come up with it. When I use the following code I can open the file, read through it and do all the necessary functions, but if I use the commented line instead of the one underneath it gives me an error at line r = L[15] like it can't read it properly anymore. What can I do about this? If more code is needed I can provide it. Thanks!
def open_file():
while True:
file = input("Enter a file name: ")
try:
open(file)
return file
except FileNotFoundError:
print("Error. Please try again.")
print()
def read_file():
#fp = open_file()
fp = open("Texas_death_row.csv")
csv_fp = csv.reader(fp)
data = []
for L in csv_fp:
r = L[15]
g = L[16]
v = L[27]
T = (r,g,v)
my_list.append(T)
return data
Your open_file function is returning the variable file, that contains the string containing the filename, not the file object (file descriptor) which is what you can read and whatnot.
You should try something like this:
def open_file():
while True:
file = input("Enter a file name: ")
try:
f = open(file)
return f # Return the "file object", not the file name
except FileNotFoundError:
print("Error. Please try again.")
print()
PS: When you're dealing with files, don't forget to close them when you're done with them.

'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.

Categories

Resources