error outputting file with python 3.0 - python

I am not sure why I am receiving this error. Everything in my program seems to be working perfectly. the program is basically a simple administration system to store username and password accounts.
the error i get is, ValueError: I/O operation on closed file.
the program successfully writes the first account, but the other accounts do not get stored in the .txt file
here is my code where i am getting the error
if savedata == 'y':
print ("\nData Successfuly Saved!")
filehandle = open(filename, "r+")
for username, password in store_data.items():
print(username, ":",password)
password = password.replace("\n","")
filehandle.write(username) # it says this line is my error
filehandle.write(":")
filehandle.write(password)
filehandle.write("\n")
filehandle.close()
else:
("Exiting Application Terminal...")

The following should fix matters:
if savedata == 'y':
print ("\nData Successfully Saved!")
with open(filename, "w") as filehandle:
for username, password in store_data.items():
print(username, ":", password)
password = password.replace("\n","")
filehandle.write("{}:{}\n".format(username, password))
else:
print("Exiting Application Terminal...")
You were closing the file after each iteration, as you only opened it once, this is why only one entry was saved.
It is also safer to use Python's with construct which will automatically take care of closing the file for you.
If you wish to append to an existing file, use "a" as the mode.

You should open the file for writing:
filehandle = open(filename, "w")

Related

I did it by the tutorial and it's not working

I found some projects on youtube, and this is one of them.
I'm trying with the password manager program. Here's the link: https://www.youtube.com/watch?v=DLn3jOsNRVE
And here's my code:
from cryptography.fernet import Fernet
'''
def write_key():
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)'''
def load_key():
file = open("key.key", "rb")
key = file.read()
file.close()
return key
key = load_key()
fer = Fernet(key)
def view():
with open('passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:", user, "| Password:",
fer.decrypt(passw.encode()).decode())
def add():
name = input('Account Name: ')
pwd = input("Password: ")
with open('passwords.txt', 'a') as f:
f.write(name + "|" + fer.encrypt(pwd.encode()).decode() + "\n")
while True:
mode = input(
"Would you like to add a new password or view existing ones (view, add), press q to quit? ").lower()
if mode == "q":
break
if mode == "view":
view()
elif mode == "add":
add()
else:
print("Invalid mode.")
continue
#this is a module that will alow you to encrypt txt-s
# pass is used as a placeholder for future code
# rstrip removes any traling chars
#split will look for the char in the arg and it will split the string there
#a append w write r read r+ read and write
#with w mode, you completely overwrite the file so be careful
#with a mode you can add smthing to the end
I followed the instructions precisely and I have no idea what could cause my problem. When I run it, I get an error message:
The guy even has his version of the code on github. I copy-pasted it and still doesn't work
On the video, does the key.key file generate itself, or not?
The only possible code that could write to the key.key file is both:
commented out; and
not called even if it were not commented out,
So, no, it's not correct to say that "the key.key file generate[s] itself".
Looking over the linked video, the presenter at some point (at 1:29:50, more precisely) had the code call that function to create the file, then removed that call and commented out that function.
Likely cause of your problem is that you made a mistake in the process somewhere(1), and this resulted in the file not being created (or being created somewhere other than where it's expected). Suggest you go back to that point in the video and re-do it.
Or, you could just create the key.key file, containing the content (taken from the video):
Raq7IMZ4QkqK20j7lKT3bxJTgwxeJFYx4ADjTqVKdQY=
That may get you going faster than revisiting the steps that the presenter took.
(1) Re your comment that "[t]he guy even has his version of the code on github", it may be that you thought you could bypass the video and just go straight to the final code. If so, that was a mistake, as the final code expects you to have run the incomplete code in order to generate the key file.
If so, I would consider that a failing of the presenter. It would have been far better to leave the keyfile-creating code in and call it, for example, when you ran the code with python the_code.py --make-key-file.

Why can't I write to a file despite using "append" mode?

I'm trying to create a basic login system with Python that only includes a username. Here is a snippet of what I'm having issues with.
I added a few usernames to the .txt file and it can find conflicts or login properly but it can't actually register a username. I've done some research and am opening the file in "append" mode and using the write command.
def register():
file1 = open("C:/test/User_Dat.txt", "a")
global username
username = str(input("Please enter a username \n")).lower()
readfile = file1.read()
if username in readfile:
print('The user', username, 'has already been created.')
welcome()
else:
print('The user', username, 'has been created!')
file1.write(username)
file1.write("\n")
file1.close()
login()
But I still get an error like this:
io.UnsupportedOperation: not writable
Why is the file not writable?
EDITED:
You are opening file in reading mode. Fix this line as follows:
file1 = open("C:/test/User_Dat.txt", "r+")
Documentation:
https://docs.python.org/3/library/functions.html#open

Loop Not Functioning well

Guys i'v got a little problem with my code. The code is supposed to check a list of numbers and group them in a text file provider based but doesn't work as expected. It only saved a single number in a file for each provider instead of multiple ones. This is my code , if anyone could help i'd be grateful.Sorry if my code is too traditional
def main():
dead = open('invalid_no.txt', 'a+')
print('-------------------------------------------------------')
print('-------------------------------------------------------')
list = input('Your Phone Numbers List : ')
base_url = "http://apilayer.net/api/validate"
params = {
'access_key': '3246123d1d67e385b1d9fa11d0e84959',
'number': '',
}
numero = open(list, 'r')
for num in numero:
num = num.strip()
if num:
lines = num.split(':')
params['number'] = lines[0]
response = requests.get(base_url, params=params)
print('status:', response.status_code)
print('-------------------------------------')
try:
resp = response.json()
print('number:', resp['valid'])
print('number:', resp['international_format'])
print('country:', resp['country_name'])
print('location:',resp['carrier'])
print('-------------------------------------')
mok = open(resp['carrier'],'w+')
if resp['carrier'] == mok.name:
mok.write(num +'\n')
except FileNotFoundError:
if resp['carrier'] == '':
print('skipping')
else:
mok = open(resp['carrier'],'w+')
if resp['carrier'] == mok.name:
mok.write(num)
else:
print('No')
if __name__ == '__main__': main()
Opening a file with mode "w" will erase the existing file and start with an empty new one. That is why you are getting only one number. Every time you write to the file, you overwrite whatever was there before. There is no mode "w+". I believe that ought to cause a ValueError: invalid mode: 'w+', but in fact it seems to do the same as "w". The fact that "r+" exists doesn't mean you can infer that there is also an undocumented "w+".
From the documentation for open():
The second argument is another string containing a few characters
describing the way in which the file will be used. mode can be 'r'
when the file will only be read, 'w' for only writing (an existing
file with the same name will be erased), and 'a' opens the file for
appending; any data written to the file is automatically added to the
end. 'r+' opens the file for both reading and writing. The mode
argument is optional; 'r' will be assumed if it’s omitted.
So, no "w+".
I think you want mode "a" for append. But if you do that, the first time your code tries to write to the file, it won't be there to append to, so you get the file not found error that you had a problem with.
Before writing to the file, check to see if it is there. If not, open it for writing, otherwise open it for appending.
if os.path.exists(resp['carrier']):
mok = open(resp['carrier'],'a')
else:
mok = open(resp['carrier'],'w')
or, if you have a taste for one-liners,
mok = open(resp['carrier'],'a' if os.path.exists(resp['carrier']) else 'w')
Also your code never calls close() on the file after it is finished writing to it. It should. Forgetting it can result in missing data or other baffling behaviour.
The best way not to forget it is to use a context manager:
with open(resp['carrier'],'a' if os.path.exists(resp['carrier']) else 'w') as mok:
# writes within the with-block here
# rest of program here
# after the with-block ends, the context manager closes the file for you.

When i try to make python write user input to a txt file, it doesn't

i am learning python, and i wanted to create a little login and register program, that writes the username and the password to a txt file (so that it can be later used), i am currently working on the register function, when i try to write to the txt files it does nothing, i tried doing a with loop, a .flush() and .close() but neither of them saves the info.
Here's my code:
username.write = input ('username > ')
password = open("password.txt", "w")
password.write = input ('password > ')
print('Welcome.')
username.close()
password.close()
What am i missing?
Edit.
Neither 3 of the solutions to the suggested question work for me...
Get your input and store them in two variables and then write them to files:
username = input ('username > ')
password = input ('password > ')
with open('usernames.txt', 'w') as userFile:
userFile.write(username)
with open('passwords.txt', 'w') as passFile:
passFile.write(password)
yourfile.open(filename,'w')
username = input()
password = input()
yourfile.write(username)
yourfile.write(password)
yourfile.close()

Python script creating unexpected blank rows in csv (using bottle, csv, os)

Initial users.csv file- columns are respectively username,real name,password.
fraud,mike ross,iloveharveynew
abc,ab isss c,coolgal
xyz,name last,rockpassnew
Algorithm-
1. Input username (from a cookie) & new-password from a html form.
2. Iterate over the csv file to print all the rows that do not contain 'username' to a new file final.csv
3. Remove users.csv file.
4. Append username,real name,new password to final.csv file.
5. Rename final.csv to users.csv
For instance, let's say user xyz was logged in and username=xyz was retrieved from cookie. The user changed the password to rockpassnewnew.
Output users.csv file-
fraud,mike ross,iloveharveynew
abc,ab isss c,coolgal
xyz,name last,rockpassnewnew
Here is the functioned defined that does this which is called from a controller-
def change(self, new_password):
errors = []
if len(new_password) < 3: errors.append('new password too short')
if errors:
return errors
else:
with open('users.csv','r') as u:
users = csv.reader(u)
with open('final.csv', 'a') as f:
final=csv.writer(f)
for line in users:
variableforchecking1 = bottle.request.get_cookie('username')
if variableforchecking1 not in line:
final.writerow(line)
os.remove('users.csv')
variableforchecking1 = bottle.request.get_cookie('username')
variableforchecking2 = bottle.request.get_cookie('real_name')
with open('final.csv', 'a') as f:
final=csv.writer(f)
final.writerow([variableforchecking1, variableforchecking2, new_password])
os.rename ('final.csv','users.csv')
return []
The controller code which calls this function is-
#bottle.get('/change')
def change():
return bottle.template('change')
#bottle.post('/change')
def changePost():
new_password = bottle.request.forms.get('new-password')
username = me.username()
errors = me.change(new_password)
if errors:
return bottle.template('change', errors=errors)
me.login(username, new_password)
return bottle.redirect('/home')
How to prevent these blank rows from being created because every time a password is changed, the number of blank rows increase considerably?
When opening a CSV file to be written to using a csv.writer, take care how you open the file.
The problem is that csv.writer does its own handling of line-endings. If a file opened with open is not opened carefully, the file object will also replace LF line-endings with CR+LF when writing data. So when both are making these changes, the line endings in the output file can become CR+CR+LF. Text editors will often interpret this as two line endings.
The fix is to open the file in binary mode in Python 2, or with newline='' in Python 3 as recommended by the documentation for the csv module. To do this, replace both occurrences of
with open('final.csv', 'a') as f:
with
with open('final.csv', 'ab') as f:
if you are using Python 2, or
with open('final.csv', 'a', newline='') as f:
if you are using Python 3.

Categories