Python: Checking file names in a directory one by one - python-3.x

I am asking for user input of a name, and I want to search in the directory of the file with the code whether a file exists that is called the same thing as the inputted name, if yes, then the program asks for a new name, if not, then it will create a file with that name. I am struggling because the code I have written only checks the first file in the directory and doesn't continue with the rest.
The code that I am having the problem with looks something like this:
import os
Name = input("Please enter name for new file")
if Name in os.listdir():
print("Sorry this name already exists, please choose another one")
break
else:
NewFile = open("Name" + ".txt", "w+")
break

You can use glob:
import glob
existing = glob.glob('*.txt')
name = '{}.txt'.format(input("Please enter name for new file"))
if name in existing:
print("Sorry this name already exists, please choose another one")
else:
newfile = open(name, "w+")

Related

Want to create a csv inside a folder if it does not exist using string parameter in python

dirLocation = "Patients Data/PatientsTimelineLog.csv"
try:
if os.path.isfile(dirLocation):
print("Directory exist." + dirLocation)
else:
print("Directory does not exists. Creating new one." + dirLocation)
os.makedirs(os.path.dirname(dirLocation))
except IOError:
print("Unable to read config file and load properties.")
Automatically creating directories with file output
Want to create a PatientsTimelineLog.csv inside Patients Data folder in one go if it does not exist. The above link is creating the folder but the csv file is not made. makedir is used to make directory but i want inside the file in it like the path given above in dirLocation.
Inside the else, you can directly use os.makedirs(dirLocation).
When you use os.path.dirname(dirLocation) you are selecting everything except the name of the csv file. That is why you are creating only the folder.
try:
folder_path = os.path.split(os.path.abspath(dirLocation))
sub_path = folder_path[0]
if os.path.isdir(sub_path):
print("Directory exist: " + dirLocation)
else:
print("Directory does not exists. Creating new one: " + dirLocation)
file_name = PurePath(dirLocation)
obj = file_name.name
filepath = os.path.join(sub_path, obj)
os.makedirs(sub_path)
f = open(filepath, "a")
except IOError:
print("Unable to read config file and load properties.")
This is the answer to my question. pathlib did lot of help in this question

How do I print back specific data from a list using user input?

In summary I'm trying to create a password manager. The Idea is that the program would ask the user input.
If user writes "new", the program asks input on the website, username and password and then store this data in a text file in the form of a List.
Now the main problem:
I want to be able to access selected data and have the program print said data from the text file to me.
For example:
I input into the program the website "google" along with username: "potato" and password: "potato"
After that, the program asks me what else I want to do. And if I write "access google", I want to program to give me back the website, username and password that are SPECIFIC to the google input.
This is necessary, as I will be adding several different inputs.
I have no idea how to do this and have no tutor. I hope someone can give a solution I can learn from.
Below you will find the base code I have come up with.
Keep in mind that I am a beginner. Thank you.
vault = open("Passvault.txt", "r+")
list = []
action = input("What do you want to do? ")
def tit():
global title
title = input("Add website: ")
return title
def user():
global username
username = input("Create username: ")
return username
def passw():
global password
password = input("Create password: ")
return password
running = True
while running:
creation = True
tit()
user()
passw()
if action == "new":
tit()
user()
passw()
#I added a class here hoping that i could create a class with an argument referencing the title
#so that when i type access "title" in the next if statement it would print back the data
#relevant to the selected title
class new(str(title)):
list.append(tit)
list.append(user)
list.append(passw)
vault.close()
if action == "access" + title:
creation = False
print(title)
print("Username: " + username)
print("Password: " + password)
vault.close()
Here is the code. This code stores the username, password, and website name in the txt file and also prints the username and password w.r.t website name.
import re # used to search patterns.
file_name = 'Passvault.txt'
while True:
action = input("What do you want to do? ")
if action == 'new':
title = input("Add website: ")
username = input("Create username:")
password = input('Create password')
#writing data into the file
with open (file_name,'a') as f:
data = f.write(f'{title} {username} {password}\n')
if 'access' in action:#if input contains access word
website = action.split()[1].strip() #storing website name which is written after access
#reading the data
with open(file_name,'r') as f:
data = f.read()
#searching for all username password related to website
username_pass = re.findall(f'{website}\s+(.*?)\n',data,re.S)#example google sachin 1234
print('Website: ',website)
print('Username, Password',username_pass)
I'm going to give you a more conceptual answer than code, because this is a more long term type of deal.
What you're going to want to do is use json files and dictionaries to store your data so you can search by keys (see the dictionaries link).
Once you've done that you're going to want to wrap everything in a while loop inside a def that gets user input like so:
def get_input():
permitted_actions = ['new', 'access', 'exit']
while True:
action = input("What do you want to do? Valid actions: new, access or type EXIT to end the program.").strip().lower()
if action not in permitted_actions:
print(f"{action} is not a valid action!")
elif action == 'new':
#call another function to do stuff here
elif action == 'access':
#call another function to do stuff here
elif action == 'exit':
print("Shutting down...")
break
I would highly recommend against creating your own actual vault for a password manager until you're much more experienced if you actually intend to use this, otherwise feed it fake passwords and whatnot and learn.
Now when you're adding website data you'll read your dictionary (see the dictionary link) and get the key associated with said website if it exists and then update the info that the user gives.
When you're accessing a website's data you just go to the dictionary (see the dictionary link) and grab the info relating to that website key if it exists.
Remember, you're going to be loading that dictionary from a json file (see the json link).
If you were to make this program an actual program someone would use you'd use a proper database of some sort (python3 has sqlite support natively) and use a database with encryption and master passwords.
I hope this points you in the right direction.
You can save the values as a dictionary with a list as the username and password then use literal_eval to convert the string dict into a dict and access the username and password as well as storing other websites with its own usernames and passwords.
website = 'google'
username,password = 'potato', 'potato'
filename = "yourfilehere"
with open(filename, w) as f:
f.write(str({website: [username,password]}))
#This will save your data as a string dictionary will the data above
#then read the file, get the dictionary and convert it then use its values
from ast import literal_eval
with open(filename, 'r') as f:
data = f.read()
data = literal_eval(data)
#Then search dictionary for website
found = data.get(website)
#Then if it was successful get the username and password
username = found[0]
password = found[1]
As long as you only have the dictionary created as a string in the file you are reading you can use this ethod to save as many website with the allocated username and password saved with it.
You can add a input() into the code to check which site the user wants the username and password for and then search for it in your dictionary.
search = input("Enter the website: ")
try:
found = data.get(search)
#add code here to get username and password
except:
print("failed to find a website matching: %s" % search")

while loop and opening file in append mode. why does the order matter?

I am following the 'python crash course', one of the practice questions ask me to open/create the txt file 'guest_book' in append mode and create a while loop to ask user input their name, at the same time append their name into the 'guest_book' txt and print that they have been logged. I have wrote the following code.
filename = 'guest_book'
with open(filename, 'a') as f:
while True:
name = input('enter name ')
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")
The problem: the while loop is successful and the final print is also successful, however when I check the guest_book txt. it does not record the inputted name. Interestingly, by simply switching the order of while loop and open txt command, it seems to work, like this:
filename = 'guest_book.txt'
while True:
with open(filename, 'a') as f:
name = input('enter name ')
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")
the only difference between the two codes are switched order of the while loop and "with open" line. Can someone explain to me why this order matters? No matter how hard I tried, I can't seem to understand the logic behind this. Thanks
Short explanation
Since your
while True
loop never ends your changes to the file are never actually "committed".
Long explanation
The whole reason we use
with open(filename, 'a') as f:
f.write("write something")
instead of
f= open("myfile.txt","w+")
f.write("write something")
f.close()
is so we don't have to close the file-access manually - only upon "f.close()" are the changes actually written to the local file!
In your code, close() is called behind the scenes once your "with"-block ends:
with open(filename, 'a') as f:
while True:
name = input('enter name ')
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")
# close() would be triggered behind the scenes here
# only after completing ALL statements in your with-block, the changes get saved to the file.
print("We never reach this point...")
Since your code never reaches that point as you have a "while true loop", the file never gets closed and the changes are never written to the file.
In your second code example, the file gets opened and closed in every iteration of the "while true"-loop as your with-block starts and ends in one iteration of the loop. This means all changes are commited every iteration of the loop.
Edit:
As MisterMiyagi has pointed out:
"f.close() releases the file handle. It also calls (the internal equivalent of) f.flush() to commit outstanding changes. The primary purpose is releasing the file handle, though."
So you can either close the entire file (as Python flushes files automatically when closing) or call f.flush() in your while-loop after writing to flush the internal buffer, but to keep the file-handle open in case you want to continue writing afterwards.
So here is a working adaption of your first code (with flush):
filename = 'guest_book'
with open(filename, 'a') as f:
while True:
name = input('enter name ')
f.write(name + '\n')
f.flush() # making sure the changes are in the file.
print(f"You have been added to the guest book, {name}")
looks like the problem is that the oppened txt file is not closed properly, the program ends by force, not alowing the closing code to run, or something like that. the reason why the:
filename = 'guest_book.txt'
while True:
with open(filename, 'a') as f:
name = input('enter name ')
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")
works is because you are constantly closing and oppening the file.
if you want the file to close, I recomend adding a save funcion or an exit function. This will make the file close properly and save itself, kind of like this:
filename = 'guest_book'
with open(filename, 'a') as f:
while True:
name = input('enter name ')
if name == 'exit':
break
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")

How to choose & save files to a directory with Python 3?

I'm having trouble making a subfolder for files to be stored into after choosing the Parent Folder or directory.
This is my current script:
import os, sys, subprocess, shutil, glob, os.path, csv
#User Chooses Folder or File Path Directory
path_new = filedialog.askdirectory()
def saveData():
serial_number = input('Scan Barcode: ')
folder_name = print('Folder Name:', serial_number)
os.chdir(path_new) #Not sure if this is necessary
if not os.path.exists(path_new):
os.makedirs(path_new)
print ('The data has been stored in the following directory:', path_new)
shutil.move('file_directory/TOTAL.csv', 'chosen_directory/%s'% (serial_number))
shutil.move('file_directory/enviro.csv', 'chosen_directory/%s' % (serial_number))
The script runs, but just not how I would like it to. Does anyone have any recommendations or an alternate solution to creating a folder and selecting it as the directory to have subfolders created and have files transferred into them?
I resolved my issue. If anyone else knows of a "cleaner" way of writing this out please update with a better answer. As of now this does exactly what I want.
Code:
import os, sys, shutil. os.path
path = filedialog.askdirectory()
def saveData():
serial_number = input('Scan Barcode: ')
folder_name = print('Folder Name:', serial_number)
path_new = os.path.join(path, '%s' % (serial_number))
if not os.path.exists(path_new):
os.makedirs(path_new)
shutil.move('C:/files/TOTAL.csv', path_new)
shutil.move('C:/files/enviro.csv', path_new)
print('The data has been stored in the following directory:', path_new)

File won't open when being passed from a function

How come it's not opening the file I put into the function? It opens when I plug the file name directly into the main program, but not when I try to pass it through the function. It gives me a FileNotFoundError.
def get_valid_filename(prompt):
'''Use prompt (a string) to ask the user to type the name of a file. If
the file does not exist, keep asking until they give a valid filename.
Return the name of that file.'''
filename = input(prompt)
if os.path.isfile(filename) == False:
print ("That file does not exist.")
filename = input(prompt)
return filename
if __name__ == '__main__':
prompt = 'enter the name of the file with unknown author:'
mystery_filename = get_valid_filename(prompt)
# readlines gives us the file as a list of strings each ending in '\n'
text = open(mystery_filename, 'r').read()
print (text)
get_valid_filename should look like this:
def get_valid_filename(prompt):
while True:
filename = input(prompt):
if os.path.exists(filename):
return filename
print('that file does not exist')

Resources