How to remove a line and replace with another line? [duplicate] - python

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 1 year ago.
I am creating an application with Pyqt5 (QT). The application do the Password Manager tasks.
I have a text file that names and passwords stored in it (encrypted).
One section of app has a tool that user can change the password from entering the name. (If you don't understand look at the picture.)
My text file is like this :
newname1|password1
newname2|password2
...
As you noticed, after "|" is the password. How can I find newname2 and just replace the password section from new password field, or remove the line and replace with a new one (for example: newname2|newpassword)?
Also I have to say that I know how to fetch data from inputs, I just want to know how to do it in python code.

Something like this should work:
out = open('file.txt', 'r').readlines()
name, newPass = 'newname2', 'NewPassword2'
for idx,line in enumerate(out):
if line.startswith(name+'|'):
out[idx] = f'{name}|{newPass}'
fBuffer = open('file.txt', 'w')
fBuffer.writelines(out)
break
else:
print('User Name not found')
You can take the name, and newPass from PyQt UI's lineEdit, read the file which has the name and the passwords stored, then iterate through these lines and check if newname2| is there in the file, if so, update the list. Then write back to the file, and exit the loop immediately.

string = '''
a|b
c|d
'''
username = 'a'
new_password = '123'
import re
new_string = re.sub(f'(?<=^{username}\|).*', new_password , string, flags=re.M)
print(new_string) # This string can be written back to the file.
Note: Not efficient but works.

Related

Prevent blank line at the end of a text file [duplicate]

This question already has answers here:
Why should text files end with a newline?
(19 answers)
Closed 11 months ago.
I have created a program in python that uses a .txt file as a database, so I save the user data there.
The data is stored in the file as follows:
Each line in the file represents a user
Users are stored as: User_ID,First Name,Last Name,Phone Number,Country
The problem arises when I try to delete a user that is in the last position of the file, because it leaves a blank line that breaks the function of listing the users in the program.
Example:
Suppose I have two users in the text file: image1
And now I delete the last user (00002): image2
So, there is a blank line, and when I add a new user, it looks like this: image3
Here is the code I use to delete users:
def delete_user(file, user_id):
with open(file, 'r+') as f:
users = f.readlines()
f.seek(0)
for user in users:
if user.split(',')[0] != user_id:
f.write(user)
f.truncate()
Code I use to add users:
def add_user(file, first_name, last_name, phone_number, country):
filesize = os.path.getsize(file)
with open(file, 'r+') as f:
if filesize == 0:
f.write(f'{"1".zfill(5)},{first_name},{last_name},{phone_number},'
f'{country}')
else:
last_line = f.readlines()[-1]
user_id = int(last_line.split(',')[0])
f.write(f'\n{str(user_id+1).zfill(5)},{first_name},{last_name},'
f'{phone_number},{country}')
Upon investigation, I realized that the problem occurs because there is a newline character (\n) left at the end of the last line, which should not be there.
So, how could I solve this problem?
A trailing newline shouldn't break your program. You seem to be using a newline as a line separator, but on Unix-like OSs, a newline is actually considered a line terminator, meaning there should be one at the end of every line.
However, you'll have a much easier time by using a standard data format. What you're using resembles CSV, so I recommend csv.DictReader and csv.DictWriter, which would also involve putting a column header in the file to label the fields. You might also consider using Pandas (e.g. pandas.read_csv() and df.to_csv()).

Finding an replacing string matches in lists Python 3

I volunteer for a modded minecraft community as a Moderators, and we deal with chatlogs frequently.
I'm building a program to take a server's chatlog, find matching usernames in it and writing them to a new file.
The way I have it at the moment, it takes the file, and converts each line into a list item, I regex the username using an expression, and write the line if it contains a match. The problem is, the way chatlogs come they are formatted like this: BOTusername, and I want to use the program to strip the BOT part before searching (makes it neater when written at the end.)
I know this is possible when you read the file normally using f.read('file.txt') but I was wondering if its possible do this with a list instead. Here is an example of what the list looks like.
The code I have so far is as follows:
import os
import re
username = 'UsernameHere'
path = os.path.dirname(__file__)
with open('chatlogs.txt', 'r') as f:
chatlogs = f.readlines()
print(chatlogs) # for debugging
# Checks the chatlogs for username matches
for line in chatlogs:
if re.match('(.*)' + username + '(.*)', line):
d = open('output.txt', 'a')
d.write(line)
If your username variable consistently looks like "BOTsomeusername", you can strip the first three characters with some simple indexing:
username = username[3:]
Thanks to Hoog for pointing me in the right direction!
I got it to work with the following code:
for line in chatlogs:
if re.match('(.*)' + username + '(.*)', line):
d = open('output.txt', 'a')
timestamp = line.split(']', 1)[0] + '] ' # includes the bracket that gets removed in the split operation
message = line.split('] ', 1)[1][3:] # saves the remainder of the message after the third character (After BOT)
d.write(timestamp + message)

How do I cycle through the lines in a .txt file, find a string in them, and then replace a word? [duplicate]

This question already has answers here:
How to find and replace multiple lines in text file?
(2 answers)
Closed 4 years ago.
I have a vehicle database in a .txt file.
Each Vehicle is in a separate line, has an ID, and can either be "active" or "inactive".
I'm writing the function "change_status()".
This function will receive an input (The ID), cycle through the .txt file to find the line with said ID, and then either replace the word "active" with the word "inactive", or the word "inactive" with the word "active".
Everything in my function is working, except one thing. I don't know how to overwrite the existing line (the one I am reading), instead of just writing a new line with the status change at the bottom of the txt file, which is what I'm getting.
def change_status():
id_to_change = input("Insert the ID of the Vehicle which you want to deactivate/activate: ")
with open("Vehicles.txt", "r+") as file:
lines = file.readlines()
for line in lines:
if id_to_change in line:
if "active" in line:
new_line = line.replace("active", "inactive")
file.write(new_line)
else:
new_line = line.replace("inactive", "active")
file.write(new_line)
else:
pass
print("VEHICLE STATUS SUCCESSFULLY CHANGED")
The easiest -- though obviously not most efficient -- solution is to rewrite the entire file. Open a different file for output, and instead of passing in the else block, write the unmodified line if no match occurred. Editing the file in place is not an operation supported directly by the filesystem, as Thomas Weller pointed out, so you would need some more logic to do anything else.

Check if a certain word is in a txt file using python

I made a program based on user input and I am using txt files with my program to check if the user input equal to the txt file.
my_age = open('c:\\file\\user_ask_about_my_age')
my_age_read = my_age.read()
user = raw_input("ask")
if user in my_Age_read:
print "I am 10 years old "
the txt file:
what is your age
how old are you
The problem is if the user types any char that is existed in my txt(ask_about...) the program print I am 10 years old.
How to make my program read the txt file like string for each line?
I need a simple way and a small code to fix my problem because I have a lot of text files.
Make sure your other file is in the same directory, then on top of your script you can do add:
import myfile
If this file contains a function to print what you want to print, you can call this function with
myfile.print_function()
I think you can achieve what you ask this way:
with open('c:\\file\\user_ask_about_my_age', 'r') as fd:
lines = fd.readlines()
lines = [line.strip('\n') for line in lines]
user = raw_input("ask")
for line in lines:
if user == line:
print "i am 10 years old "

Input to a seperate file (let the user write text in a python program as it writes to a file)

How do I let the user write text in my python program that will transfer into a file using open "w"?
I only figured out how write text into the seperate document using print. But how is it done if I want input to be written to a file? In short terms: Let the user itself write text to a seperate document.
Here is my code so far:
def main():
print ("This program let you create your own HTML-page")
name = input("Enter the name for your HTML-page (end it with .html): ")
outfile = open(name, "w")
code = input ("Enter your code here: ")
print ("This is the only thing getting written into the file", file=outfile)
main ()
First off, use raw_input instead of input. This way you capture the text as a string instead of trying to evaluate it. But to answer your question:
with open(name, 'w') as o:
o.write(code)
You can also surround that code in a loop that keeps repeating until the user hits a certain key if you would like them to be able to hit enter when typing their html file.
EDIT: Example of loop to allow continuous user input:
with open(name, 'w') as o:
code = input("blah")
while (code != "exit")
o.write('{0}\n'.format(code))
code = input("blah")
That way, the loop will keep running until the user types in "exit" or whatever string you choose. The format line inserts a newline into the file. I'm still on python2 so I'm not completely sure how input handles newlines, but if it includes it, feel free to remove the format line and use it as above.
def main():
print ("This program let you create your own HTML-page")
name = input("Enter the name for your HTML-page (end it with .html): ")
outfile = open(name),'w')
code = input ("Enter your code here: ")
outfile.write(code)
main ()
This does not accept multi line code entries. You will need an additional module for that.

Categories