Deleting a line from txt file - python-3.x

I have a txt file with lists of names like this
Name1
Name2
Name3
I want to delete the line with "Name2" in it, if Name2 is in the list. I got this code:
f = open(list,'r')
if("Name2" in f.read().splitlines()):
lines = f.readlines()
f.close()
f = open(badhumanslist, "w")
for line in lines:
if line != "Name2" + "\n":
f.write(line)
f.close()
The problem is that this code empties the whole file. I don't see my error, it should rewrite all the lines, except the one with "Name2"

You already read the whole file in line 2: f.read(). Then, lines = f.readlines() returns an empty list.
def read_all():
with open(filename, "r") as file:
return file.read()
content = read_all()
lines = content.splitlines()
if "Name2\n" in lines:
with open(filename, "w") as file:
for line in lines:
if line != "Name2\n":
file.write(line)

Related

How to Read ' n ' line from a text file and store it to another text file in python

I have a text file as "file_in.txt".I want read the first three lines from that
file and Write the those three lines read from "file_in.txt" to a new file
called "file_out.txt".
After write it, read "file_out.txt" and Print it's contents
file_in = "file_in.txt"
file_out = "file_out.txt"
data = ""
# read the first 3 lines of file_in.txt
with open(file_in, 'r') as f:
for i in range(3):
data += f.readline()
# write to file_out.txt
with open(file_out, 'w') as f:
f.write(data)
# read the content of file_out.txt
with open(file_out, 'r') as f:
content = f.read()
print(content)

How to find and replace string in a file using input of line number in python

My requirement is to find a file from a directory and then in that file find LOG_X_PARAMS and in that append a string after the first comma this is what i am having for now
import os, fnmatch
def findReplacelist(directory, finds, new_string, file):
line_number = 0
list_of_results = []
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
with open(filepath, 'r') as f:
for line in f:
line_number += 1
if finds in line:
list_of_results.append((line_number))
print(list_of_results)
def get_git_root(path):
Path = "E:\Code\modules"
file_list=["pb_sa_ch.c"]
for i in file_list:
findReplacelist(Path , "LOG_1_PARAMS", "instance", i)
The example line is below change
LOG_X_PARAMS(string 1, string 2); #string1 andd string2 is random
this to
LOG_X_PARAMS(string 1, new_string, string 2);
I can find the line number using LOG_X_PARAMS now using this line number I need to append a string in the same line can someone help solving it ?
This is how I would do the task. I would find the files I want to change, read then file line by line and if there is a change in the file, then write the file back out. Heres the approach:
def findReplacelist(directory, finds, new_string, file):
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
find_replace(finds, new_string, filepath)
def find_replace(tgt_phrase, new_string, file):
outfile = ''
chgflg = False
with open(file, 'r') as f:
for line in f:
if tgt_phrase in line:
outfile += line + new_string
chgflg = True
else:
outfile += line
if chgflg:
with open(file, 'w') as f:
f.write(outfile)

Delete multiple line in a text file but it is deleting only last line

def delet_line(exp_res):
filename = "C:\\Users\\beher\\Desktop\\my.txt"
exp_res_sl = exp_res.splitlines()
#print('file name is ',filename)
with open(filename, "r") as f:
lines = f.readlines()
for expres_line in exp_res_sl:
print(expres_line)
with open(filename, "w") as f:
for line in lines:
if line.strip("\n") != expres_line:
f.write(line)
delet_line("Mohan\nmohan")
Here i am trying to delete the a multiline string passing as argument but it deletes only the last line of the passing argument pls help| thanks in advance.
Maybe like so:
def delete_line(skip_lines):
filename="C:\\Users\\beher\\Desktop\\my.txt"
with open(filename, "rt") as f:
lines = f.readlines()
with open(filename, "wt") as f:
for line in lines:
if line.strip('\n') not in skip_lines:
f.write(line)
delete_line(['Mohan', 'mohan'])

Reading each line from text file

I have a script which reads each line from text file. but somehow it prints all at once. I want to run one line end and run next. here is the code.
f = open('textfile.txt', 'r')
file= f.read()
for x in file:
print(x, file.strip())
comSerialPort.write(x.encode('utf-8'))
Use readlines instead of read
with open('textfile.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
# do stuff with each line
Use with statement and then iterate lines.
Ex:
with open('textfile.txt', 'r') as infile:
for line in infile:
print(line)
comSerialPort.write(line.strip().encode('utf-8'))
Note: read() reads the entire content of the file.

Python-2.7 write to file

I have this script:
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
if a ==58:
print (line)
line1 = "google.ca"
f.write(line1)
print line
a = a+1
f.close()
I want to keep my file but only to change what is written on line 58 to "google.ca"
then save it
using linux: mint-17.2
# Read data from file
with open('yourfile.txt', 'r') as file:
# read all line in the file to data array
data = file.readlines()
# change data on line 58 (array start from 0)
data[57] = 'Data you need to change'
# Write data back
with open('yourfile.txt', 'w') as file:
file.writelines(data)
You need to decide whether you want to write a new file (with print) or change the old file (with r+ mode and f.write). You will probably be happiest if you write a new file.
dataRead = []
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
if a == 58:
line = "google.ca"
dataRead.append(line)
a = a+1
f.close()
f2 = open("/some/new/file","w")
for line in dataRead:
f2.write(line)
f2.close()
With the answer of Adisak Anusornsrirung I wrote it like this:
with open('sss.txt','r') as file:
data = file.readlines()
print (data[14])
file.close()
data[14] = "some data here"+"\n"
with open ("sss.txt", 'w') as file:
file.writelines(data)
file.close()
f = open("sss.txt", 'r')
print (f.read())
f.close()

Resources