I am a beginner in Python and therefore am not sure why I am receiving the following error:
TypeError: invalid file: []
for this line of code:
usernamelist=open(user_names,'w')
I am trying to get an input of a username and password, write them to files, and then read them.
Here is the rest of my code:
user_names=[]
passwords=[]
username=input('Please enter a username')
password=input('Please enter a password')
usernamelist=open(user_names,'w')
pickle.dump(userName,usernamelist)
usernamelist.close()
usernamelist=open(user_names,'r')
loadusernames=pickle.load(usernamelist)
passwordlist=open(passwords,'w')
pickle.dump(password,passwordlist)
passwordlist.close()
passwordlist=open(passwords,'r')
loadpasswords=pickle.load(passwordlist)
All answers would be appreciated. Thanks.
Based on your script, this may help. It creates a 'username.txt' and 'password.txt' to store input username and password.
I use python2.7, input behaves differently between in python2.7 and python3.x.
"""
opf: output file
inf: input file
use with instead of .open .close: http://effbot.org/zone/python-with-statement.htm
for naming rules and coding style in Python: https://www.python.org/dev/peps/pep-0008/
"""
import pickle
username = raw_input('Please enter a username:\n')
password = raw_input('Please enter a password:\n')
with open('username.txt', 'wb') as opf:
pickle.dump(username, opf)
with open('username.txt') as inf:
load_usernames = pickle.load(inf)
print load_usernames
with open('password.txt', 'wb') as opf:
pickle.dump(password, opf)
with open('password.txt') as inf:
load_passwords = pickle.load(inf)
print load_passwords
Related
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
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()
I want to create a simple log-in account program in Python using the "CSV" library. Here is the code:
import csv
account_password = ""
with open("accounts.csv") as csvfile:
reader = csv.reader(csvfile)
while True:
username = input("\nEnter username: ")
# Checks if username exists
for row in reader:
if row[0] == username:
account_password = row[1] # Get user's password
break
password = input("Enter password: ")
# Check if password is valid
if password == account_password:
break
else:
print("Username/password is incorrect. Try again.")
print("\nSuccessfully logged in!")
Here is how my CSV file looks like. The first column is the usernames and the second one is the passwords:
Tim,myPassword
John,monkey32
Fred,WooHoo!
When I tried to test my program in IDLE, I noticed an unusual log-in issue.
If I log in with the correct credentials, then the program works perfectly fine:
If I log in with incorrect log in details, the program works as expected:
But here is the issue. After entering incorrect log in details, the program asks the user to try again. This is done with a "while loop" in my code. Yet when I "try again", but with the correct details, the program thinks the log-in details are incorrect:
Here is the same issue with another user from the csv file:
I would love it if anyone could let me know what is wrong with my code.
Please also show the full updated code along with an explanation for why the code in the answer is working and the difference between it and mine.
Thank you.
It looks like that for row in reader running only once
try change the order of your code
Try to open the file inside the while True: like this:
while True:
with open("accounts.csv") as csvfile:
reader = csv.reader(csvfile)
should work fine because you close the file before each iteration
for row in csv.reader(csvfile) goes through the file line by line, once. After the file is exhausted, it doesn't do anything. You can instead load it into memory as a dictionary (provided it is not too large, otherwise you probably need a DB):
import csv
account_passwords = dict()
with open("accounts.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
account_passwords[row[0]] = row[1]
while True:
username = input("\nEnter username: ")
password = input("Enter password: ")
if username in account_passwords and \
account_passwords[username] == password:
print("\nSuccessfully logged in!")
break
else:
print("Username/password is incorrect. Try again.")
If you're doing this for anything serious, consider hashing the passwords and using getpass.getpass instead of input for reading passwords.
csv.reader(%filename%) is generator.
Python generators can be processed only once. So when your enter incorrect details generator goes up to last row and found nothing. When your code return to "while True" reader will be empty and "for row in reader:" will not return any values.
Correct (or at least working) version should be something like this:
import csv
account_password = ""
def get_pass_from_file(username):
with open("accounts.csv") as csvfile:
for item in csv.reader(csvfile):
if item[0] == username:
return item[1]
if __name__ == '__main__':
while True:
username = input("\nEnter username: ")
account_password = get_pass_from_file(username)
if account_password is None:
print("Username not found. Try again.")
continue
password = input("Enter password: ")
if password == account_password:
break
else:
print("Username/password is incorrect. Try again.")
print("\nSuccessfully logged in!")
I am trying to make a simple bruteforcer for rar files. My code is...
import rarfile
file = input("Password List Directory: ")
rarFile = input("Rar File: ")
passwordList = open(file,"r")
for i in passwordList:
try :
rarfile.read(rarFile, psw=i)
print('[+] Password Found: '+i)
except Exception as e:
print('[-] '+i+' is not a password ')
passwordList.close()
I think this has to do with my use of the module, because when I input a password list that I am 10000% sure contains the password to the rarFile, it prints the exception.
The real problem here is that you are catching all exceptions, not just the one you want. So use except rarfile.PasswordRequired: That will show you that the error is not a missing password. Instead there is no function read in the rarfile module.
Have a look at some Documentation. Rar encryption is per file, not per archive.
You need to create a object from the RarFile class and try the password on each file in the archive. (or just the first if you know that is encrypted)
import rarfile
file = input("Password List Directory: ")
rarFilename = input("Rar File: ")
rf = rarfile.RarFile(rarFilename)
passwordList = open(file,"r")
first_file = next(rf.infolist)
for i in passwordList:
password = i.rstrip()
try:
rf.open(first_file, psw=password)
print(password, "found")
except rarfile.PasswordRequired:
print(password,"is not a password")
When you open and read lines from a file, the "new line" character is kept
at the end of the line. This needs to be stripped from each line.
for i in passwordList:
password = i.rstrip()
try :
rarfile.read(rarFile, psw=password)
print('[+] Password Found: '+password)
This is my basic code:
fname = input("What is the name of the file to be opened")
file = open(fname+".txt", "r")
message = str(file.read())
file.close()
What I want to do is essentially make sure the file the program is attempting to open exists and I was wondering if it was possible to write code that tries to open the file and when it discovers the file doesn't exist tells the user to enter a valid file name rather then terminating the program showing an error.
I was thinking whether there was something that checked if the code returned an error and if it did maybe made an variable equal to invalid which an if statement then reads telling the user the issue before asking the user to enter another file name.
Pseudocode:
fname = input("What is the name of the file to be opened")
file = open(fname+".txt", "r")
message = str(file.read())
file.close()
if fname returns an error:
Valid = invalid
while valid == invalid:
print("Please enter a valid file name")
fname = input("What is the name of the file to be opened")
if fname returns an error:
Valid = invalid
etc.
I guess the idea is that you want to loop through until your user enters a valid file name. Try this:
import os
def get_file_name():
fname = input('Please enter a file name: ')
if not os.path.isfile(fname+".txt"):
print('Sorry ', fname, '.txt is not a valid filename')
get_file_name()
else:
return fname
file_name = get_file_name()
Going by the rule Asking for forgiveness is better then permission
And using context-manager and while loop
Code :
while True: #Creates an infinite loop
try:
fname = input("What is the name of the file to be opened")
with open(fname+".txt", "r") as file_in:
message = str(file_in.read())
break #This will exist the infinite loop
except (OSError, IOError) as e:
print "{} not_available Try Again ".format(fname)