Using line.replace twice in the same line - python

I am trying to use line.replace such that I can replace two separate variables in the same line before moving onto the next line.
lets say the text file "file.txt' is:
(1.00)
(2.00)
(3.00)
I would like to replace the ( and ) with and empty space for each line. Here is what I have.
file=open('file.txt', 'r')
file_1=open('file_1.txt', 'w')
for line in file:
x=line.replace('(', "")
file_1.writelines(x)
file_2=open('file_1.txt', 'r')
file_3=open('file_2.txt', 'w')
for line in file_2:
y=line.replace(')', "")
file_3.writelines(y)
Is there a way to make this more efficient?
Thank you for your help,
Kyle

You just need to call the replace function a second time after you do it the first time:
for line in file:
x=line.replace('(', "")
x=x.replace(')', "")
file_1.writelines(x)
Or, you could even call the replace function twice on the same line:
for line in file:
x=line.replace('(', "").replace(')', "")
file_1.writelines(x)

You can make this much simpler. As others have said, you can call replace twice, because it does return a string, so you could do...
for line in file:
x=line.replace('(', "").replace(')', "")
file_1.writelines(x)
You don't actually need the x either, so you can combine them into one line. The works because the replace function keeps returning a string.
for line in file:
file_1.writelines(line.replace('(', "").replace(')', ""))
And now that it's a one line for loop, we can make this even simpler into a list comprehension. Making the entire program
file=open('file.txt', 'r')
file_1=open('file_1.txt', 'w')
[file_1.writelines(line.replace('(', "").replace(')', "")) for line in file]
Don't hesitate to ask questions.

Related

Python: Remove first instance only of string from text file

I have been removing the desired lines from a text file by reading it in and rewriting each line if the string(s) I wish to remove are not present, using the following.
with open('infile.txt', 'r') as f:
lines = f.readlines()
with open('outfile.txt', 'w+') as f:
for line in lines:
if line.strip("\n") != "Desired text on line to remove":
f.write(line)
This works fine for all but one of the lines I need to remove which only contains.
1.
This is the first instance of (1.) in the file, and always will be in the files I'm editing; however it is repeated later in the text file and these later instances must be kept - is it possible to remove only the first instance of this text?
If I've understood your question correctly then you want to get rid of first '1.' and keep the rest. It can be done in multiple ways, like below code.
with open('infile.txt', 'r') as f:
lines = f.readlines()
with open('outfile.txt', 'w+') as f:
t = '1.'
for line in lines:
line = line.strip("\n")
if line != "Desired text on line to remove" and line != t:
f.write(line)
f.write("\n")
if line == t:
t = None
One of them is by simply using logical operators (which I've used) and create a variable you want to remove. Which in my case as t. Now use it to filter the first instance. Thereafter change its value to None so that in the next instance it will always be a True statement and the condition to run or not depends on if line is equal to our desired text or not.
P.S.- I've added some more line of codes like line = line.strip("\n") and f.write("\n") just to make the output and code clearer. You can remove it if you want as they don't contribute to clear the hurdle.
Moreover, if you don't get the desired output or my code is wrong. Feel free to point it out as I've not written any answers yet and still learning.

How do I remove the "\n" characters when reading my file but deleting one variable then replacing it

I am trying to make a program that reads from a file and deletes one specific line inside of it and then puts all the data stored back to the file separated with a new line. The file uses this format:
Jones|20|20|00
bob|30|19|90
James|40|19|80
So I want to delete (backup contains this and is the line I want to delete)
bob|30|19|90
but the code that I am using takes away the new line and doesnt replace it but when I try to add \n to it the file doesn't want to read as it does this (adds 2 "\n"s):
Jones|20|20|00
James|40|19|80
I am using this code below:
def deleteccsaver(backup):
lockaccount =""
lockaccount = lockaccount.strip("\n")
with open('accounts_project.txt','r+') as f:
newline=[]
for line in f.readlines():
newline.append(line.replace(backup, lockaccount).strip("\n"))
with open('accounts_project.txt','w+') as f:
for line in newline:
f.writelines(line +"\n")
f.close()
resetlogin()
Please help as I dont know how to add the \n back without it appearing as "\n\n"
Without the "\n "it appears as:
Jones|20|20|00James|40|19|80
Any suggestions:
What I am doing here is reading the entire file at once, please don't do this if you have a very very big file. After reading all file contents at once, I am making a list out of it using "\n" as a delimiter. Read about split function in python to know more about it. Then from the list I am replacing the backup with lockaccount, as you have been doing the same, these are the names of variables that you are using, hope I did not confuse between them in this case. Then it will be saved to a new file after adding new line after each element of list, i.e. each line of the previous file. This will cause the result file to have all the contents as previous file, but removing what you wanted to remove. I see that lockaccount is itself an empty string, so adding it might create a newline in your file. In case you dont want lockaccount to replace the backup variable in the file, just remove the backup from the list using contents.remove(backup) instead of contents[contents.index(backup)] == lockaccount keeping the rest of the code same. Hope this explains better.
def deleteccsaver(backup):
lockaccount =""
lockaccount = lockaccount.strip("\n")
with open('accounts_project.txt','r+') as f:
contents = f.read().split("\n")
if backup in contents:
contents[contents.index(backup)] = lockaccount
new_contents = "\n".join(contents)
with open('accounts_project.txt','w+') as f:
f.write(new_contents)
resetlogin()
You are priting a newline character after each element in the list. So, if you replace a line with the empty string, well, you will get an empty line.
Try to simply skip over the line you want to delete:
if line == backup:
contiune
else:
lines.append(...)
PS. There is room for improvment in the code above, but I'm on the phone, I will get back with an edit later if nobody gets ahead of me
You can try to add newline = '\n'.join(newline) after your first for loop and then just write it into the accounts_project.txt file without a loop.
The code should then look like:
def deleteccsaver(backup):
lockaccount =""
lockaccount = lockaccount.strip("\n")
with open('accounts_project.txt','r+') as f:
newline=[]
for line in f.readlines():
newline.append(line.replace(backup, lockaccount).strip("\n"))
newline = '\n'.join(newline)
with open('accounts_project.txt','w+') as f:
f.write(newline)
f.close() # you don't necessarily need it inside a with statement
resetlogin()
Edit:
Above code still results in
Jones|20|20|00
James|40|19|80
as output.
That's because during the replacement loop an empty string will be appended to newline (like newline: ['Jones|20|20|00','','James|40|19|80']) and newline = '\n'.join(newline) will then result in 'Jones|20|20|00\n\nJames|40|19|80'.
A possible fix can be to replace:
for line in f.readlines():
newline.append(line.replace(backup, lockaccount).strip("\n"))
with
for line in f.readlines():
line = line.strip('\n')
if line != backup:
newline.append(line)
def deleteccsaver(backup):
lockaccount =""
lockaccount = lockaccount.strip("\n")
with open('accounts_project.txt','r+') as f:
contents = f.read().split("\n")
if backup in contents:
contents.remove(backup)
new_contents = "\n".join(contents)
with open('accounts_project.txt','w+') as f:
f.write(new_contents)
resetlogin()

How do I make a list from a textfile in Python?

I have a txt file that contains names which are separated by lines but with some empty lines.
When I execute the following code, every second name gets ommitted in the output array.
Why is that?
def get_string_list(string_textfile):
list = []
file = open("names.txt", "r")
for line in file:
line = file.readline()[:-1]
list.append(line.lower())
return list
when you iterate the file
for line in file:
# you read line just now it exists
line = file.readline()
# uh oh you just read another line... you didnt do anything with the first one
dont mix iteration of a file with readline in general (in fact i think modern python versions will throw an error if you try to mix these two)
if all you want is a list of lines you can do any of the following
lines = list(file)
# or
lines = file.readlines()
you can get only non_empty lines and strip newlines as follows
lines_stripped = list(filter(None,(l.strip() for l in file)))
not super pythonic but its nice and terse and pretty clear what its doing
modify for statements like following:
for line in file:
list.append(line.strip().lower())
list = [name for name in list if name]
last line added to remove empty line.

While in python does not print all the rows

Dear I want display the three rows contained in txt file but I don't know why the following code does not works.
The code is
f=open("dati.txt","r")
riga=f.readline()
while riga!="":
print(f.readline())
riga=f.readline()
f.close()
because you are reading two lines in a loop. The readline moves the cursor one down each time you call it. So what happens there with the second call of readline() you actually skip it(in the print log)
Also checking for end of file should not be done on empty string, because you may hit an empty line before the end of the file. Try this instead:
with open('somefile') as openfileobject:
for line in openfileobject:
do_something()
and or/check this thread(where I copied the snippet from): What is the perfect counterpart in Python for "while not EOF"
The reason why your program is not printing all the rows in the file, but rather only every even numbered row, is because you use f.readline() multiple times in the while statement.
f=open("dati.txt","r")
riga=f.readline() # This line means that the variable "riga" contains the first line in your file
while riga!="":
print(f.readline()) # here you do f.readline() again, which means that what you are printing is the second line
riga=f.readline() # This line reads in the third line into the "riga" variable.
f.close()
What I think you are looking for, is to print the contents of the riga variable instead, like this
while riga != "":
print(riga)
riga = f.readline()
I should also mention that tstoev's answer also has a good approach at printing each line in a file. It does solve the same problem, but it does not point out why your code doesn't work.
Your code reads three lines and prints only one:
f=open("dati.txt","r")
riga=f.readline() # Reads a line into riga
while riga!="":
print(f.readline()) # Reads a line and prints it
riga=f.readline() # Reads a line into riga
f.close()
So the problem seems that you read lines into riga, but never print riga.

How to delete a specifil line by line number in a file?

I'm trying to write a simple Phyton script that alway delete the line number 5 in a tex file, and replace with another string always at line 5. I look around but I could't fine a solution, can anyone tell me the correct way to do that? Here what I have so far:
#!/usr/bin/env python3
import od
import sys
import fileimput
f= open('prova.js', 'r')
filedata = f,read()
f.close ()
newdata = "mynewstring"
f = open('prova.js', 'w')
f.write(newdata, 5)
f.close
basically I need to add newdata at line 5.
One possible simple solution to remove/replace 5th line of file. This solution should be fine as long as the file is not too large:
fn = 'prova.js'
newdata = "mynewstring"
with open(fn, 'r') as f:
lines = f.read().split('\n')
#to delete line use "del lines[4]"
#to replace line:
lines[4] = newdata
with open(fn,'w') as f:
f.write('\n'.join(lines))
I will try to point you in the right direction without giving you the answer directly. As you said in your comment you know how to open a file. So after you open a file you might want to split the data by the newlines (hint: .split("\n")). Now you have a list of each line from the file. Now you can use list methods to change the 5th item in the list (hint: change the item at list[4]). Then you can convert the list into a string and put the newlines back (hint: "\n".join(list)). Then write that string to the file which you know how to do. Now, see if you can write the code yourself. Have fun!

Categories

Resources