I am writing a program to read a text file of zip codes that should print the location of the zip code when the correct number is input. However, I am having trouble writing the error message. I have tried various methods and cannot get the error message to print, here is what I have:
try:
myFile=open("zipcodes.txt") #Tries to open file user entered
except:
print "File can't be opened:", myFile #If input is invalid filename, print error
exit()
zipcode = dict() #List to store individual sentences
line = myFile.readline() #Read each line of entered file
ask = raw_input("Enter a zip code: ")
if ask not in line:
print "Not Found."
else:
for line in myFile:
words = line.split()
if words[2] == ask:
zipcode = words[0:2]
for value in zipcode:
print value,
Some sample ZIP codes:
Abbeville AL 36310
Abernant AL 35440
Acmar AL 35004
Adamsville AL 35005
Addison AL 35540
Adger AL 35006
Akron AL 35441
Alabaster AL 35007
I'm not sure of the significance of enterFile. You should see the error message if you remove enterFile from the exception because it doesn't appear to be defined.
From the beginning:
try:
myFile=open("zipcodes.txt")
except:
print "File can't be opened:", myFile # if open fail then myFile will be undefined.
exit()
zipcode = dict() # you creating dict, but you never add something into it.
line = myFile.readline() # this will read only first line of file, not each
ask = raw_input("Enter a zip code: ")
if ask not in line:
# it will print not found for any zipcode except zipcode in first line
print "Not Found."
else:
# because you already read 1 line of myFile
# "for line in " will go from second line to end of file
for line in myFile: # 1 line already readed. Continue reading from second
words = line.split()
if words[2] == ask: # If you don't have duplicate of first line this will never be True
zipcode = words[0:2]
# So here zipcode is an empty dict. Because even if "ask is in line"
# You never find it because you don't check line
# where the ask is (the first line of file).
for value in zipcode:
# print never executed becouse zipcode is empty
print value,
I believe that you need two phases in this program:
Read zipcodes.txt and build your directory.
Ask the user for a ZIP code; print the corresponding location.
Your current "positive" logic is
else:
for line in myFile:
words = line.split() # Get the next line from zipcodes.txt
if words[2] == ask: # If this ZIP code matches the input,
zipcode = words[0:2] # assign the line's three fields as a list.
# Variable zipcode now contains a single line's data, all three fields.
# You threw away the empty dictionary.
for value in zipcode: # Print all three fields of the one matching line.
print value,
Needed Logic (in my opinion)
# Part 1: read in the ZIP code file
# For each line of the file:
# Split the line into location and ZIP_code
# zipcode[ZIP_code] = location
# Part 2: match a location to the user's given ZIP code
# Input the user's ZIP code, "ask"
# print zipcode[ask]
Does this pseduo-code get you moving toward a solution?
Related
This question already has answers here:
Using Python to Remove All Lines Matching Regex
(3 answers)
Closed 3 months ago.
I want to search a text file for the user input and delete the line that contains it.Below is the text file.
course work.txt:-
Eric/20/SL/merc/3433
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
If the user input is 'Eric', I want the line containing 'Eric' to be deleted and then the text file to be saved as below
Updated course work.txt:-
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
Here is the code I created for that with the help of the very very small knowledge I have and some websites.
with open('course work.txt','r') as original:
#get user input
word = input('Search: ')
# read all content of file
content = original.read()
# check if string present in file
if word in content:
print('User input exsists')
confirmation = input('Press enter to delete')
if confirmation == '':
import os
with open('course work.txt', 'r') as original:
with open('temp.txt', "w") as temporary:
for line in original:
# if user input contain in a line then don't write it
if word not in line.strip("\n"):
temporary.write(line)
os.replace('temp.txt', 'course work.txt')
else:
print('Driver doesn't exsist')
What's happening here is,
1.open the course work.txt and read it
2.get the user input and search course work.txt for that user input
3.if that user input is found in the course work.txt, open a new file called temp.txt
write the all lines except the line that contains the user input into temp.txt
5.over write temp.txt on course work.txt
When I run the code it gives me a 'PermissionError: [WinError 5] ' error.The temp.txt file get created. It contains all the lines except the line i want to delete which is great, but it doesn't over write on the original file. Is there way to solve this or is there a more PYTHONIC way to do the exact same thing?
You can write a function to take care of that and also by making good use of shutil to copy temp.txt after writing in order to update source-work.txt .
import shutil
def modify_original_file():
word = input('Search: ').strip().lower()
track = 0
with open("course-work.txt", 'r') as original:
with open("temp.txt", "w") as temporary:
# read all lines of file
content = original.readlines()
# check if string present in file
word_found = False
for line in content:
if word in line.lower():
word_found = True
break
if word_found == True:
print('User input exist')
confirmation = input('Press Enter to delete: ')
if confirmation == '':
for line in content:
if word not in line.lower():
temporary.write(line)
track += 1
else:
print("Driver doesn't exist")
if track > 0:
# Update course-work.txt by copying temp.txt file
shutil.copyfile("temp.txt", "course-work.txt")
modify_original_file()
Terminal: Enter Eric or eric for search.
Search: eric
Output: updated source-work.txt:
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
So basically I am making a program that writes the .txt file and changes the names in form by last to first like Woods, Tiger and turn them into usernames in this form twoods. They have to be formatted all in lower case and I think I messed up my code somewhere. Thanks!
The code I tried, below:
def main():
user_input = input("Please enter the file name: ")
user_file = open(user_input, 'r')
line = user_file.readlines()
line.split()
while line != '':
line = user_file.readline()
print(line.split()[-1][0][0:6]+line.split()[0][0:6]).lower() , end = '')
user_file.close()
if __name__ == "__main__":
main()
try this:
line = "Tiger Woods"
(fname, lname) = line.split(" ")
print(f'{fname[0:1]}{lname}'.lower())
There appear to be a couple of little issues preventing this from working / things that can be improved,
You are trying to split a list which is not possible. This is a string operation.
You are manually closing the file, this is not ideal
The program will not run as you are not using __name__ == "__main__"
Amended code,
def main():
user_input = input("Please enter the file name: ")
with open(user_input, 'r') as file_handler:
for line in file_handler:
print((line.split()[-1][0][0:6] + line.split()[0][0:6]).lower(), end='')
if __name__ == "__main__":
main()
If i understand your problem correctly, you want to read Surname,Name from a file line by line and turn them into nsurname formatted usernames.
For that, we can open and read the file to get user informations and split them line by line and strip the \n at the end.
After that, we can loop the lines that we read and create the usernames with given format and append them to an array of usernames.
Code:
# Get filename to read.
user_input = input("Please enter the file name: ")
# Open the given file and readlines.
# Split to lines and strip the \n at the end.
user_names = []
with open(user_input,'r') as user_file:
user_names = user_file.readlines()
user_names = [line.rstrip() for line in user_names]
print("User names from file: " + str(user_names))
# Loop the user informations that we read and split from file.
# Create formatted usernames and append to usernames list.
usernames = []
for line in user_names:
info = line.split(',')
username = (info[1][0:1] + info[0]).lower()
usernames.append(username)
print("Usernames after formatted: " + str(usernames))
Input File(test.txt):
Woods,Tiger
World,Hello
Output:
Please enter the file name: test.txt
User names from file: ['Woods,Tiger', 'World,Hello']
Usernames after formatted: ['twoods', 'hworld']
I am trying to make a login system sort of program but whenever there is more than 1 line of data the code resets the entire CVS file. I need someone to help me with why it's happening. It happens when I choose opt == 2 and search for the name entered 2nd onwards...
reading the CSV file:
try:
df = pd.read_csv('accounts.csv')
for i in range(len(df['name'])):
names.append(df['name'][i])
balances.append(df['balance'][i])
dec_pass = bytes(df['password'][i], 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(dec_pass)
decrypted = decrypted.decode()
passwords.append(decrypted)
except:
with open('accounts.csv', 'w') as f:
f.write(',name,balance,password')
names = []
balances = []
passwords = []
def name_ser(name):
found = False
for i in range(len(names)):
if names[i] == name:
found = True
return found, names.index(name)
else:
found = False
return found
def main_menu():
print('Welcome!\nPlease Choose from the following options...')
print('1: Create an account\n2: Login ')
opt = int(input('Enter Your Choice: '))
if opt == 1:
name_search = input('Enter Name... ')
found, _ = name_ser(name_search)
if found == True:
print("Account Already excites!")
else:
acc_creation(name_search)
print('Account created!')
if opt == 2:
name_search = input('Enter your login name: ')
found, indx = name_ser(name_search)
if found == True:
password = input('Enter your password: ')
dec_pass = bytes(passwords[indx], 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(dec_pass)
decrypted = decrypted.decode()
if password == decrypted:
print('Logged in!')
else:
print('Invalid username or password')
before:
after:
the other thing is when I try to create more than 2 accounts it gives an error and also resets the CSV file. it works fine for the first 2 accounts but gives an error on the second one.
def acc_creation(name):
names.append(name)
balances.append(0)
password_enter = input('Create a Password: ')
encry_p = password_enter.encode()
f = Fernet(key)
encry_pass = f.encrypt(encry_p)
encry_pass = encry_pass.decode('ascii')
passwords.append(encry_pass)
new_df = pd.DataFrame(np.column_stack([names, balances, passwords]),
columns=['name', 'balance', 'password'])
new_df.to_csv('accounts.csv', encoding='utf-8', sep=',',
header=True, na_rep=0, index=True)
Error:
Traceback (most recent call last):
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 91, in <module>
main_menu()
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 79, in main_menu
acc_creation(name_search)
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 54, in acc_creation
new_df = pd.DataFrame(np.column_stack([names, balances, passwords]),
File "<__array_function__ internals>", line 5, in column_stack
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/lib/shape_base.py", line 656, in column_stack
return _nx.concatenate(arrays, 1)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 2 has size 1
I believe this may possibly be tied to the name_ser method but cannot be totally sure without seeing what it is doing.
What CSV library are you using? CSV? Panda?
Also, you may want to try adding a return value to the name_ser method to return the index and not have to go through the list again to match it to the password.
Good luck!
--- Edit ---
Every time that you are executing it is opening up the file again and re-writing: ,name,balance,password
If you are wanting to execute more than once, you will need to either:
Write a while loop for main where it will continuously call main_menu()
Check to see if the CSV already exists. If it does, open in read and copy everything and paste it into a new writeable CSV. If it doesn't, move to create the new writeable CSV.
There are quite a few issues here we should address before we try to fix your problem:
your code sample is incomplete, the function name_ser as well as your names and passwords lists are missing
passwords must never be stored in plaintext (unless this code is just for yourself to learn stuff). Please read about Key derivation functions
CSV is not a database where you can easily edit entries inplace. The only safe way to handle this is to overwrite the entire CSV file each time you make a change or to use another data structure (which I would strongly recommend)
I have a file which contains my passwords like this:
Service: x
Username: y
Password: z
I want to write a method which deletes one of these password sections. The idea is, that I can search for a service and the section it gets deleted. So far the code works (I can tell because if you insert print(section) where I wrote delete section it works just fine), I just don't know how to delete something from the file.
fileee = '/home/manos/Documents/python_testing/resources_py/pw.txt'
def delete_password():
file = open(fileee).read().splitlines()
search = input("\nEnter Service you want to delete: ")
if search == "":
print("\nSearch can't be blank!")
delete_password()
elif search == "cancel":
startup()
else:
pass
found = False
for index, line in enumerate(file):
if 'Service: ' in line and search in line:
password_section = file[index-1:index+3]
# delete password_section
found = True
if not found:
print("\nPassword for " + search + " was not found.")
delete_password()
Deleting a line from the file is the same as re-writing the file minus that matching line.
#read entire file
with open("myfile.txt", "r") as f:
lines = f.readlines()
#delete 21st line
del lines[20]
#write back the file without the line you want to remove
with open("myfile.txt", "w") as f:
f.writelines(lines)
I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
#This function writes to the testFile.docx file
outfile = open('testFile.docx', 'w')
outfile.write('Hello World\n')
outfile.write('It is raining outside\n')
outfile.write('Ashley is sick\n')
outfile.write('My dogs name is Bailey\n')
outfile.write('My cats name is Remi\n')
outfile.write('Spam Eggs and Spam\n')
outfile.close()
infile = open('testFile.docx', 'r')
testFileContent = infile.read()
infile.close()
print(testFileContent)
main()
First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
with open(x) as f:
data = f.readlines()
for i in range(5):
print(data[i])
except:
print('No such a file found!')
Using a simple function,
def hello_user():
user_input = input('Enter file name: ')
try:
with open(user_input, 'r') as f:
data = f.readlines()
data = data[:5]
for o in data:
print(o.strip())
except FileNotFoundError:
print('Not found ')
hello_user()
It asks for a file name
If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)
We select only the first 5 lines
We iterate through the list and remove the extra whitespace character(e.g \n).
If the file was not found, we catch the exception.
input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
file = input("Please enter a file name")
with open(file, 'r') as f:
lines = f.readlines()
print(lines[:5])
The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.