Change text in file with Python - python

def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False

You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()

Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)

To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?

Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()

Related

Creating an object from a list of attributes in a file, Python

I have a file full of lines, where each line has attributes for a bank account object. Example of file layout:
1,IE33483,alex,1,100,20,s
2,IE30983,joe,1,0,20,c
3,IE67983,tom,1,70,20,s
Im trying to create some code that will search this file for user input (e.g they enter their id which is the first element of each line), and will use these all 3 attributes to create an object. Any help? This is what I have tried so far, but it doesn't seem to work for a file with more than one line:
accid=input("Enter ID of account to manage:\n")
f = open("accounts.txt", "r")
for line_str in f:
split_line = line_str.split(",")
accid2 = split_line[0].strip()
if split_line[6] == 's':
for line in split_line:
if accid2 == accid:
current_acc=SavingsAccount(accid, split_line[1],
split_line[2],
split_line[3],
split_line[4],
split_line[5],
split_line[6])
print("Logged in as: ")
print(current_acc.accid)```
You can do something like this - no need to iterate through the parts within each line.
def get_account_by_id(id, type_)
with open("accounts.txt") as f:
for line in f:
parts = line.split(",")
if parts[0] == id and parts[6] == type_:
return SavingsAccount(*parts)
accid = input("Enter ID of account to manage:\n")
account = get_account_by_id(accid, type_="s")
if account is not None:
print(f"Logged in as {account.accid}")
Or better, if your file is a valid CSV file, use the CSV module
import csv
def get_account_by_id(id, type_)
with open("accounts.txt") as f:
for row in csv.reader(f):
if row[0] == id and row[6] == type_:
return SavingsAccount(*row)

How do I select certain lines in a text file from python script?

So I'm making a python script where you can create an account and that account is saved in a text file. When you try to log in, it will look in the text file for your username and then move down a line for the password but I don't know how to move down a line after finding the username. Any help would be appreciated. :)
Update -
import time
import sys
print ("Do you have an account?")
account = input()
if account == "Yes":
print ("Enter your username")
enterUsername = input()
with open ("Allusers.txt") as f:
if enterUsername in f.read():
print ("Enter your password")
enterpassword = input()
if enterpassword in f.read():
print ("Logged in")
if enterpassword not in f.read():
print ("Wrong password")
if account == "No":
print ("Create a username")
createUsername = input()
with open ("Allusers.txt") as f:
if createUsername in f.read():
print ("Username already taken")
sys.exit()
if createUsername not in f.read():
print ("Create a password")
createPassword = input()
with open ("Allusers.txt") as f:
if createPassword in f.read():
print ("Password not available")
sys.exit()
if createPassword not in f.read():
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createUsername + "\n")
file_object.close()
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createPassword + "\n")
file_object.close()
print ("Done")
This is still work in progress and most likely still has errors here and there.
Assumin that your file look like this:
Adam
password
John
12345678
Horacy
abcdefg
Romek
pass1234
You can try this example:
user = "Horacy"
password = "abcdefg"
with open( "users.txt", "r" ) as file:
for line in file:
if user == line.strip():
if password == file.readline().strip():
print( "Correct" )
break
As stated if someones password equals someones username iterating over all lines and checking may return faulty results you'll want to check only usernames as you iterate, so zipping every other line you can check the username only and return the password:
def get_password(file, username):
with open(file, "r") as f:
data = f.readlines()
for user, pw in zip(data[::2], data[1::2]):
if user.strip() == username:
return pw.strip()
def get_password(file, username):
lines = open(file, "r").readlines() # get the lines from the file
for i, line in enumerate(lines):
if line == username: # if the current is the username, return the following line
return lines[i + 1]
You should only search in usernames. The data[::2] will select usernames.
with open("filename", "r") as f:
data = f.read().splitlines()
email = "email#email"
if email in data[::2]:
id_email=data[::2].index(email)
row=id_email*2-1
password=data[row+1]

Remove a line from a text file using only the first index

Let's say I have a text file containing the following details:
name1,address,more details
name2,address,more details
name3,address,more details
I take an input and it finds the row like this:
name = str(input("Enter Name to delete record:\n"))
with open("theFile.txt", "r") as file:
for x in file:
seperated = x.split(',')
if seperated[0] == name:
print(x)
This prints the whole row of the details. Now here's the part I'm stuck on. How can I delete this row? I've tried this but it doesn't do anything to the file.
with open("theFile.txt", "r") as file:
lines = file.readlines()
with open("theFile.txt", "w") as file:
for line in lines:
if line.strip("\n") != x:
file.write(line)
else:
print("Row removed")
I've seen other posts where you can remove the row by comparing it to the whole row but how can I do this by comparing the first index only?
One way is:
with open("theFile.txt") as f:
items = list(f)
name = input("Enter Name to delete record:\n") # input is always a string
with open("theFile.txt", "w") as f:
[f.write(x) for x in items if not x.split(",")[0] == name]
The last line can also be written as:
for line in items:
parts = line.split(",")
if not parts[0] == name:
f.write(line)
Demo
It should work like this:
name = str(input("Enter Name to delete record:\n"))
lines=[]
with open("theFile.txt", 'r') as file:
for x in file:
seperated = x.split(',')
if seperated[0] == name:
print(seperated)
print("Row removed")
else:
lines.append(x)
with open("theFile.txt", "w") as file:
for line in lines:
print(line)
file.write(line)
name = str(input("Enter Name to delete record:\n"))
all_lines=[]
with open("theFile.txt", "r") as file:
for x in file:
all_lines.append(x.strip("\n"))
for line in all_lines:
seperated = line.split(',')
if seperated[0] == name:
all_lines.remove(line)
print("Row removed")
with open("theFile.txt","w") as f:
for line in all_lines:
f.write(str(line)+"\n")

Why the context of the file cannot read from the txt file?

I have creat a new empty txt file, but the code below read and write it.
f = open('users.txt', 'r+')
users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
for i in range(4):
name = input('Input Username: ')
passwd = input('Input password: ')
c_passwd = input('Confirm password again: ')
if len(name.strip()) != 0 and name not in users and len(passwd.strip()) != 0 and passwd == c_passwd:
users[name]= {'passwd':passwd, 'role':1} #insert new data, role 1: Customer; role 2: Restaurant; role 3: Admin
f.seek(0)
f.truncate() #clear file
f.writelines(str(users)) #write data to file from dict
print('Congratulations, Register Success. ')
f.close()
break
elif len(name.strip()) == 0:
print('Username could not be empty. Remain %d chance' %(3-i))
elif name in users:
print('Username repeat. Remain %d chance' %(3-i))
elif len(passwd.strip()) == 0:
print('Password could not be empty. Remain %d chance' %(3-i))
elif c_passwd != passwd:
print('Password not same. Remain %d chance' %(3-i))
#log in
f = open('users.txt', 'r', encoding='utf8')
users = eval(f.read())
for count in range(3):
name = input('Input Username: ')
password = input('Input password: ')
if name in users and password == users[name]['passwd']:
print('Log in successful!')
break
else:
print('Username or/and Password is/are wrong,You still have %d chance'%(2-count))
f.close()
The System showed
Traceback (most recent call last):
File "C:/Users/zskjames/PycharmProjects/Fit5136/Register, log in.py", line 4, in <module>
users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Do anybody could tell me how to fix that? And how to avoid this mistakes in the future.
You probably want your text file to contain JSON, in order to easily interact with it and turn it into a dict.
In order to do that, you would need to replace your eval with a json.load:
import json
with open('users.txt', 'r+') as f:
users = json.load(f)
# rest of your code
In order for it to work, your text file should look something like the following:
{"John Doe": {"passwd": "somepass", "role": 1}}
In addition, you need to replace:
f.writelines(str(users)) #write data to file from dict
to:
json.dump(users, f)

search for string in json file

i have a dictionary which the user enters values in at the beginning, those values are then stored into a txt file in json format. The goal is for the user to be able to search the json file with a string of their choice. I have tried a variety of ways but have come up unsuccesful. The code below shows if the user enters 's' then they will be prompted to enter a search term. the code then loads the json file and stores the information from the file into a "list" called "data", then the code attempts to search every item within the list and compare it to the searchTerm inputted from the user
code that puts the users input into the txt file (json format)
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter puncline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for item in data:
if searchTerm in data:
print ('found it')
pass
import json
import sys
import os
data = []
if os.stat("data.txt").st_size != 0 :
file = open('data.txt', 'r')
data = json.load(file)
print(data)
choice = input("What's your choice ?")
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter punchline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for sub_dict in data:
if searchTerm in sub_dict['setup']:
print(sub_dict['punchline'])
pass
# or you could modify the last for loop, like this:
for dict in data:
if searchTerm in dict['setup'] or searchTerm in dict['punchline']:
print('found!')
pass
You could do it like this:
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter punchline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for item in data[0].items():
if searchTerm in str(item[1]):
print ('found it')
pass
# or the for loop could be like this
for sub_dict in data:
if searchTerm in sub_dict['setup'] or searchTerm in sub_dict['punchline']:
print('found!')

Categories

Resources