I was wondering if there was a way to tell the user that no file in a directory they specified has the file extension they are looking for. The only way I could think of uses an if/else, but would be tripped up if any other file extension exists in the directory. I was able to find something but it was bash: Listing files in a directory that do not end with vXXX and not exactly what I was looking for.
Here is an example of a directory:
out-30000000.txt.processed
out-31000000.txt.processed
out-32000000.txt.processed
out-33000000.txt.processed
out-34000000.txt.processed
nope.csv
If I use the following code:
def folder_location():
location = raw_input("What is the folder containing the data you like processed located? ")
#location = "C:/Code/Samples/Dates/2015-06-07/Large-Scale Data Parsing/Data Files"
if os.path.exists(location) == True: #Tests to see if user entered a valid path
print "You entered:",location
if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
print ""
file_extension(location)
else:
folder_location()
else:
print "I'm sorry, but the file location you have entered does not exist. Please try again."
folder_location()
def file_extension(location):
file_extension = raw_input("What is the file type (.txt for example)? ")
print "You entered:", file_extension
if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
print ""
each_file(location, file_extension)
else:
file_extension(location)
def each_file(location, file_extension):
try:
column = (raw_input("Please enter column name you want to analyze: ")) #Using smcn
print "You entered:",column
if raw_input("Is this correct? Use 'Y' and 'N' to answer. ") == "Y":
print ""
sort_by(location,file_extension,column)
else:
each_file(location,file_extension)
except TypeError:
print "That is not a valid column name. Please try again."
each_file(location,file_extension)
def sort_by(location, file_extension, column):
content = os.listdir(location)
for item in content:
if item.endswith(file_extension):
data = csv.reader(open(os.path.join(location,item)),delimiter=',')
col_position = get_columnposition(data.next(),column)
to_count = sorted(data, key=operator.itemgetter(col_position))
count_date(to_count, location)
else:
print "No file in this directory ends with " + file_extension
I get:
No file in this directory ends with .processed
and then the rest of my output (code not posted here).
Is there a way for me to say (I'm going to put it in a code block just to show how it works in my mind):
def file_extension(location):
file_extension = raw_input("What is the file type (.txt for example)? ")
print "You entered:", file_extension
if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
print ""
each_file(location, file_extension)
else:
file_extension(location)
def each_file(location, file_extension):
try:
column = (raw_input("Please enter column name you want to analyze: ")) #Using smcn
print "You entered:",column
if raw_input("Is this correct? Use 'Y' and 'N' to answer. ") == "Y":
print ""
sort_by(location,file_extension,column)
else:
each_file(location,file_extension)
except TypeError:
print "That is not a valid column name. Please try again."
each_file(location,file_extension)
def sort_by(location, file_extension, column):
content = os.listdir(location)
for item in content:
if item.endswith(file_extension):
data = csv.reader(open(os.path.join(location,item)),delimiter=',')
col_position = get_columnposition(data.next(),column)
to_count = sorted(data, key=operator.itemgetter(col_position))
count_date(to_count, location)
if no item.endswith(file_extension):
print "No file in this directory ends with " + file_extension
Any help would be greatly appreciated. If it would help, I could edit in the rest of my code I have at the moment.
Thanks!
Your logic should be the following:
Ask for the directory
Ask for the extension
Check if any file ends with that extension
If there is at least one file, then ask for the column
To make all this easier, use csv and glob:
import glob
import csv
import os
directory = input('Please enter the directory: ')
extension = input('Please enter the extension (.txt, .csv): ')
files = list(glob.glob(os.path.join(directory, extension)))
if not files:
print('Sorry, no files match your extension {} in the directory {}'.
format(extension, directory))
else:
for file_name in files:
col = input('Enter the column number for {}'.format(file_name))
with open(file_name, 'r') as thefile:
reader = csv.reader(thefile, delimiter=',')
for row in reader:
try:
do_something(row[col])
except IndexError:
print('Column {} does not exist'.format(col))
Related
I am a beginner coder here and I am trying to do a simple registration/login system using an external csv file.
my issue--> let's say I have an existing user "john" when my program promts for a name during registration and I enter the letter j or jo or joh
output --> user existed
how can I solve this issue?
import csv
name = input("register your name: ")
name=name.replace(" ", "")
with open("datafile.csv","r") as file:
content=file.read()
loop=True
while loop!=False:
if name in content :
name = input("name taken pls try again: ")
name=name.replace(" ", "")
else:
loop=False
password=input("new password: ")
with open("datafile.csv","a+",newline="") as file:
f=csv.writer(file)
f.writerow([name,password])
def main():
with open("datafile.csv","r") as file:
file_reader = csv.reader(file)
user_find(file_reader)
file.close()
def user_find(file):
user = input("Enter your username: ")
for row in file:
if row[0] == user:
print("username found", user)
user_found = [row[0],row[1]]
pass_check(user_found)
break
else:
print("not found")
def pass_check(user_found):
user = input("enter your password: ")
if user_found[1] == user:
print("password match")
else:
print("password not match")
main()
name in content checks whether name is anywhere in the string content. name may be any string whatsoever, so 'jo' in 'john,his_password' will happily find that 'jo' is indeed a substring of the content and evaluate to True.
You should actually parse the CSV:
existing_names = set() # in case the file is empty
with open("datafile.csv") as file:
existing_names = {
existing_name
for (existing_name, _) in csv.reader(file)
}
while True:
if name in existing_names:
name = input("name taken pls try again: ")
name = name.replace(" ", "")
else:
break
I want to be able to open directories by only typing first digits of the directory number.
In C:/Orders/ I have a couple of directories:
40_0
125_15
4012_0
4040_127
5445_0
4_67
If I type in the input "4012" it opens the 4012 directory, but when I type "4" it opens all directories that start with 4, I need to open only one.
Also, when I type some numbers that don't match any existing directory, it prints("Nothing found") as many times as many directories are in current directory. I have no clue how to solve this.
This is what I tried:
os.chdir("C:/Orders")
while True:
orderNo = input("Type order number: ")
for filename in os.listdir():
if filename.startswith(orderNo):
os.startfile(filename)
else:
print("Nothing found.")
The following should print the first one that match and print only once in case of non match the "Nothing found."
while True:
orderNo = input("Type order number: ")
for filename in os.listdir():
if filename.startswith(orderNo):
os.startfile(filename)
break
else:
print("Nothing found.")
#Pay attention to where the else is put. This is a nice feature of python (the for else)
you may use:
from pathlib import Path
from glob import glob
subfolders = list(map(Path, glob('"C:/Orders/*/')))
name_subfolder = {p.name : p for p in subfolders}
orderNo = input("Type order number: ")
while orderNo != 'exit':
f = (e for e in name_subfolder.keys() if e.startswith(orderNo))
try:
os.startfile(next(f))
except StopIteration:
print("Nothing found.")
orderNo = input("Type order number: ")
you are taking all the subfolders and build a dict name_subfolders who has as key the name of each subfolder and the absolute path, then you can take input and check if any subfolder name starts with a given input if is the case then will open your folder for you if not will give you a not found message
I am new to coding and have a list of lists that I need to search.
I want to see what lists contained in the larger list have the variable full_choice as the 3rd item in the sequence.
All lists that contain third_choice i need to print to a txt file.
the code below works and adds exactly what I need it to to the file, however I need the function to start again if there is no match for the variable full_choice.
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have tried inserting an else: at the end of the code however while that has ends up creating the file it doesn't write anything to it.
Tried to fix your indentation. I'm guessing you wanted something like this:
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I just moved the else block forward to align with the if block you had a few lines before.
As #Haken Lid suspected, please fix indentation:
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').
replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have this code:
class CleanUp:
def __init__(self,directory):
self.directory = directory
def del_items(self,*file_extensions):
"""deletes specified file extensions in specificied directory"""
removed_files = [file for file in os.listdir(self.directory) for ext in file_extensions if ext in file]
for index ,file in enumerate(removed_files):
print(str(index + 1) + ": " + file + "\n")
confirm_delete = input("are you sure you want to delete all {0} files? y|n ".format(len(removed_files)))
while confirm_delete.lower() not in ("y","n"):<--------- this while loop
confirm_delete = input("are you sure you want to delete all {0} files? y|n ".format(len(removed_files)))
if confirm_delete.lower() == "y":
for file in removed_files:
try:
os.remove(os.path.join(self.directory,file))
except:
pass
print("successfully deleted {0} files".format(len(removed_files)))
else:
print("deletion cancelled goodbye")
pass
directory = input("please enter a directory ")
while not os.path.exists(directory):
print("{0} is not a valid directory \n".format(directory))
directory = input("please enter a directory ")
file_extensions = input("please put in file extensions of files that need deleting. seperate them by one space ")
file_extensions = file_extensions.split()
desktop = CleanUp(directory)
deleted_files = desktop.del_items(*file_extensions)
This line works
while confirm_delete.lower() not in ("y","n"):
however, when I try to do
while confirm_delete.lower() != "y" or confirm_delete.lower() != "n":
the while loop never passes.
I'm sure it has something to do with the or but
why doesn't it work when done like that?
Because that condition will always be true; there is no string value which is both "y" and "n" at the same time. Use and instead.
I wrote this sample program that is meant to open a text file (database1.txt) from the computer, and display the results that are currently in the file. Then prompt the use if their name is in the document, if it is it should print the contents of the text file then close, otherwise it should prompt the user to enter their first name, then the program writes the name into the same text document, then prints the contents of the text file again so that the user can see the new added data. I have typed the code, and somehow it keeps saying I have a syntax error. I checked a few times and I cannot fix the error. I was wondering if someone could take a look and if they might be able to explain the error to me. Thank you
#This program reads/writes information from/to the database1.txt file
def database_1_reader ():
print('Opening database1.txt')
f = open('database1.txt', 'r+')
data = f.read()
print data
print('Is your name in this document? ')
userInput = input('For Yes type yes or y. For No type no or n ').lower()
if userInput == "no" or userInput == "n"
newData = input('Please type only your First Name. ')
f.write(newData)
f = open ('database1.txt', 'r+')
newReadData = f.read()
print newReadData
f.close()
elif userInput == "yes" or userInput == "ye" or userInput == "y"
print data
f.close()
else:
print("You b00n!, You did not make a valid selection, try again ")
f.close()
input("Presss any key to exit the program")
database_1_reader()
print is a function in py3.x:
print newReadData
should be :
print (newReadData)
Demo:
>>> print "foo"
File "<ipython-input-1-45585431d0ef>", line 1
print "foo"
^
SyntaxError: invalid syntax
>>> print ("foo")
foo
statements like this:
elif userInput == "yes" or userInput == "ye" or userInput == "y"
can be reduced to :
elif userInput in "yes"