Python replace word for line [duplicate] - 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

Print Statement executing twice Python

When a user enters an input and if it is not available, the print executes twice
How do I fix it???
if ask.lower() == 'open':
with open(filename, 'r') as f:
contents = f.read().splitlines()
search_name = input("What is your name? ")
for line in contents:
if line.find(search_name) != -1:
print(line)
else:
print("Unable to find your name")
output:
Unable to find your name
Unable to find your name
Here is a more robust construct:
if ask.lower() == 'open':
with open(filename) as f:
name = input('What is your name? ')
for line in f:
if name in line:
print(line)
break
else:
print('Unable to find your name')
You are invoking the print command for every entry in your file!
Let me clarify, for the name that you get as input into search_name, you are looping over EVERY LINE that you have read from a file (in your case it seems that the file had 2 lines).
Your if cluase is not what you want. What you need is something like this:
if ask.lower() == 'open':
with open(filename, 'r') as f:
contents = f.read().splitlines()
search_name = input("What is your name? ")
is_found = false
for line in contents:
if line.find(search_name) != -1:
is_found = true
print(line)
if not is_found:
print("Unable to find your name")

How can I delete a specific line from a txt file based on user input?

How do I go about deleting a specific line in a text file that is based on the user input?
def remove():
delete_value = input("Enter the value you wish to delete: ")
with open("values.txt", "r") as f:
lines = f.readlines()
with open("values.txt", "w") as f:
for line in lines:
if line.strip("\n") != delete_animal:
f.write(line)
Any help is appreciated, thank you!
Try this -
def remove():
num = []
delete_animal = input("Enter the name of the animal you wish to delete: ")
file = open("txt file", "r")
file.seek(0)
list_of_lines = file.readlines()
file.seek(0)
lines = file.read().splitlines()
file.close()
if delete_animal not in lines:
print("That line does not exist, please try again")
for word in lines:
num.append(0)
if delete_animal == word:
file = open('txt file','w')
list_of_lines[len(num)-1] = ""
file.writelines(list_of_lines)
print('Animal Deleted')
This should delete the line in which the input animal is there
EDIT-
It should be A3_s3902169_stock.txt. You need to add that extension .txt
def remove():
delete_value = input("Enter the value you wish to delete: ")
with open("value.txt", "r") as f:
file = f.readlines()
with open("value.txt", "w") as f:
for line in file:
# we will skip the line that contains our target word
# in this case the delete_animal
words = line.strip("\n").lower().split(' ')
if delete_value.lower() not in words:
f.write(line)
Input file:
line 1
line 2
line 3
line 4
may name is sudipto
my name is sudiptoandiloveprogramming
user input: sudipto
Output file after delete:
line 1
line 2
line 3
line 4
my name is sudiptoandiloveprogramming

How to read external file in python?

i need to be able to save and get usernames and passwords from an external file. this is what i have done so far however it constantly says that username or password is incorrect even when i enter it correctly. does anyone know how to fix this problem.
this is my current code
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open("gcsetask.txt", "a")
file.write(username + ":" + password)
file.write('\n')
file.close()
welcome = "y"
time.sleep(0.4)
print("now lets login")
break
print("Passwords do NOT match!")
if welcome == "y":
while True:
login1 = input("Enter username:")
login2 = input("Enter Password:")
file = open("gcsetask.txt", "r")
data = file.readlines()
file.close()
if data == (login1 + ":" + login2):
print("Welcome")
break
print("Incorrect username or password.")
Three methods to read a file
read() It returns the read bytes in form of a string.
fileObject.read()
You can also define, how many bytes to read by
`fileObject.read([n]) //If n is not define, it will read the whole file`
readline([n]) It reads the line and return in the form of string, It only read single line
fileObject.readline([n])
readlines() It reads all the lines of the file and return each line a string element in a list
fileObject.readlines()
Hope it helps
I have changed the code to look at each line of that file. Allowing multiple users.
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open("gcsetask.txt", "a")
file.write(username+":"+password)
file.write('\n')
file.close()
welcome = "y"
time.sleep(0.4)
print("now lets login")
break
print("Passwords do NOT match!")
if welcome == "y":
while True:
login1 = input("Enter username:")
login2 = input("Enter Password:")
file = open("gcsetask.txt", "r")
data = file.readlines()
file.close()
for line in data:
if line == (login1+":"+login2+"\n"):
print("Welcome")
break
else:
print("Incorrect username or password.")
The function readlines() saves each line in a string inside a list.
If a file contains-
first line
second line
readlines() gives: ['first line','second line']
Try accessing them using index such as data[0] and data[1]
When you use file.readlines(), the function returns a list of all lines in the file. Thus, when you define data as:
data = file.readlines()
if you print(data), you get something similar to:
['user:pass\n'] # note the the \n at the end
Then, in the following line:
if data == (login1+":"+login2):
you're trying to compare a string (login1+":"+login2) with a list, which is always False because they have different type.
Changing the condition to:
if login1+":"+login2 in data:
should fix this problem (but you'll have a different one, see below).
About the trailing \n:
file.readlines() splits the lines in a list, but does not remove the newline character. This will cause your test to still fail always, because you don't account for it in the test.
Possible solutions are:
1) include the \n in the string you search:
if '{}:{}\n'.format(login1,login2) in data:
2) read the whole file and use splitlines instead, which will remove the newline characters
data = file.read().splitlines()
The readlines method returns the list of lines which you need to iterate on it to find the appropriate login information.
data = file.readlines()
login_info = f"{login1}:{login2}\n"
if login_info in data:
print("Welcome")
break
And also you can remove \n from the end of each line using splitlines.
data = file.read().splitlines()
login_info = f"{login1}:{login2}"
if login_info in data:
print("Welcome")
break
And another alternative is remove \n from parsed lines manually.
data = [line.rstrip('\n') for line in file.readlines()]
login_info = f"{login1}:{login2}"
if login_info in data:
print("Welcome")
break

How to replace/change element in txt.file

Im trying to replace a cetain element in a txt file.
let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber.
let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.
def change_number():
while True:
try:
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
datafile = open('telephonelist.txt')
if name in open('telephonelist.txt').read():
for line in datafile:
if line.strip().startswith(name):
line = line.replace(name,newNumber)
print('I found', name)
quit()
else:
print('I could not find',name+',','please try again!\n')
continue
except ValueError:
print('nn')
change_number()
This i telephonelist.txt
Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.
def change_number():
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
with open('telephonelist.txt', 'r+') as file:
data = file.read().splitlines()
data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
file.seek(0)
file.write("\n".join(data))
file.truncate()
change_number()

create a table using file contents python

if the file for example contains:
A: GHJIG
B: AHYFASF
C: IYDDFG
f = open(example.txt)
I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.
input: A
output: GHJIG
how to do it?
Try this:
with open('test.txt','r') as file:
content = file.readlines()
my_dict = {}
for line in content:
split = line.split(':')
my_dict[split[0]] = split[1]
input = raw_input("Choose a letter")
if input in my_dict:
print my_dict[input]
It would be better to use a OrderedDict from collections, because default dictionary has a not a precise order.
Try the solution below, you can provide a useful message if the user enters any alphabet which is not present in your txt file.
with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj:
content = file_obj.readlines()
sample_dict = {}
for value in content:
sample_dict[value.split(':')[0]] = value.split(':')[1]
input_key = raw_input("Please enter an alphabet: \n")
print sample_dict.get(input_key, "No value exists")

Categories