Replace line in text file using python - python

This is my program:
filetest = open ("testingfile.txt", "r+")
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for line in filetest:
line = line.rstrip ()
if not ID in line:
continue
else:
templine = '\t'.join(map(str, list))
filetest.write (line.replace(line, templine))
filetest.close ()
I'm trying to replace an entire line containing the ID entered in filetest with templine (templine was a list joined into a string with tabs), and I think the problem with my code is specifically this part filetest.write (line.replace(line, templine)), because when I run the program, the line in the file containing ID doesn't get replaced, but rather templine is added to the end of the line.
For example, if the line in filetest found using the ID entered was "Goodbye\tpython," now it becomes "Goodbye\tpythonHello\tTesting\tFile\t543210" which is not what I want. How do I ensure that line "Goodbye\tpython" is replaced by templine "Hello\tTesting\tFile\t543210", not appended?

As you are reading from the file the file pointer moves as well and it can cause problems. What I would do is first read the file and prepare the "new file" that you want, and then write it into the file, as shown in the code below:
filetest = open ("testingfile.txt", "r")
lines = filetest.readlines()
filetest.close()
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for i in range(len(lines)):
lines[i] = lines[i].rstrip()
if ID not in lines[i]:
continue
else:
templine = '\t'.join(map(str, list))
lines[i] = templine
with open("testingfile.txt", "w") as filetest:
for line in lines:
filetest.write(line + "\n")
I didn't change the logic of the code but be aware that if your file has, for example, a line with the number "56" and a line with the number "5", and you enter the ID "5", then the code will replace both of those lines.

Related

How do I delete a certain line (given a line #) in a file through python?

I want to delete a line of text from a .txt file given an integer corresponding to the txt file's line number. For example, given the integer 2, delete line 2 of the text file.
I'm sort of lost on what to put into my program.
f = open('text1.txt','r+')
g = open('text2.txt',"w")
line_num = 0
search_phrase = "Test"
for line in f.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
print("text found a line" , line_num)
decision = input("enter letter corresponding to a decision: (d = delete lines, s = save to new txt) \n")
if decision == 'd':
//delete the current line
if decision == 's':
//save the current line to a new file
Any help is appreciated! Thanks :)
This way:
with open('text1.txt','r') as f, open('text2.txt',"w") as g:
to_delete=[2,4]
for line_number, line in enumerate(f.readlines(), 1):
if line_number not in to_delete:
g.write(line)
else:
print(f'line {line_number}, "{line.rstrip()}" deleted')
Here it goes.
f = open('data/test.txt','rb')
text = f.readlines() # all lines are read into a list and you can acess it as a list
deleted_line = text.pop(1) #line is deleted and stored into the variable
print(text)
print(deleted_line)
f.write(text) # here you save it with the new data, you can always delete the data in the file to replace by the new one

read and get specific int line of the text file into variable on python

a_file = open('file.txt')
string = 'a word'
flag = 0
index = 0
for line in a_file:
index += 1
if string in line:
break
index -= 1
lines_to_read = [index]
for position, line in enumerate(a_file):
if position in lines_to_read:
file = line
print(line)
I found the line where 'a word' is located, and I want to get those line into a variable
but it only reads the first line of the text file
how can I fix it
You can simply iterate through the lines, and assign the line to a previous created string variable, if the condition is met, that the string occurs in a line of the file:
a_file = open('file.txt')
string = 'a word'
res_line = ""
for line in a_file:
if string in line:
res_line = line
print(res_line)
a_file.close()
you could also create a list which contains every line in that the string occurs:
a_file = open('file.txt')
string = 'a word'
res = [line for line in a_file if string in line]
print(res)
a_file.close()
#Maicon has it, though in python you don't even need the global variable, you can create and set desired_line in the if statement and its namespace will extend to the entire function containing the if statement:
a_file = open('file.txt')
string = 'a word'
for line in a_file:
if string in line:
desired_line = line
break
print(desired_line)
a_file.close()
What you can do is check for string in the line. This will do for you.
a_file = open('all.txt')
string = 'a word'
flag = 0
index = 0
for position, line in enumerate(a_file):
if string in line: #=== if 'a word' in line
file = line
pos=position+1
break
print(file,"Line Number: ",pos)
However if more number of the same words are there, you can use a dict to get the line numbers and the value.
a_file = open('all.txt')
string = 'f'
dictionary={}
flag = 0
index = 0
for position, line in enumerate(a_file):
if string in line:
file = line
pos=position
dictionary.update({pos+1:[file.strip("\n").strip(),file.count(string)]})
if dictionary!={}:
print("\n------- Statistics --------\n")
print("Total Items found: ",len(dictionary),"\nTotal Occurences: ",sum([dictionary.get(x)[1] for x in dictionary]))) #=== Get the sum of all numbers
for key, value in dictionary.items():
print("-------------------------")
print("Line: "+value[0],"\nNumber of occurrences: ",value[1],"\nLine Number: ",key)
else:
print("Oops. That word was no found. Check you word again.")

Iterating Through Text File Only Printing First Line

I am trying to check if the variable 'account' is in a text file (variable 'line'). I iterated through the file and printed out 'line'. Doing so allowed be to print the whole text file. I then added if statement to check if an account is in the file and did a print as well. Only the first line of the text file printed when i used that last 'if' statement.
for account, email,master_name in zip(account_numbers, email_address,master_name):
fbl_acct_check_q = f"""SELECT * FROM TEST
WHERE account_no = '{account.replace("-","")}'"""
fblacctcursor.execute(fbl_acct_check_q)
for col_acct_fbl_check in fblacctcursor.fetchall():
account_status = col_acct_fbl_check[6]
with open(sumbstatementfilepath) as sbfile:
lines = sbfile.readlines()
for line in lines:
line = line.split()
print(line)
if account_status == 4 and account not in line:
fbl_account_email()
print(line)
break

Script adding line break in middle of string

The script is adding a line break right after the curly braces while writing both strings right after the username. I would think this is because of my source text file has encoding in it adding the breaks but as far as I can tell it does not. Am I misunderstanding how write works? Something simple I'm missing. Been looking at this too long and need a new set of eyes.
users_list = []
users = input("File of User's ")
user_file = open(users + '.txt', 'r')
for i in user_file:
users_list.append(i)
sql_file = open('sql.txt', 'w')
sql_file.write("SELECT MACHINE.NAME AS SYSTEM_NAME, SYSTEM_DESCRIPTION,
MACHINE.IP, MACHINE.MAC, MACHINE.ID as TOPIC_ID FROM MACHINE WHERE
((MACHINE.USER_NAME = '{}') OR ".format(users_list[0]))
for i in users_list:
sql_file.write("(MACHINE.USER_NAME = '{}')".format(i))
sql_file.write(" OR ")
The output of the file looks like this:
SELECT MACHINE.NAME AS SYSTEM_NAME, SYSTEM_DESCRIPTION, MACHINE.IP, MACHINE.MAC, MACHINE.ID as TOPIC_ID FROM MACHINE WHERE ((MACHINE.USER_NAME = 'hnelson
') OR (MACHINE.USER_NAME = 'hnelson
') OR (MACHINE.USER_NAME = 'snery
') OR (MACHINE.USER_NAME = 'jherman
change your line 7 and 8
for i in user_file:
users_list.append(i)
to
for i in user_file:
users_list.append(i.strip())
and it should work as expected.
It is because i is a line from user_file and it ends with \n. i.strip() removes the trailing newline.

How to find and replace different strings in a file at a time?

As per my know this may work for one condition but it is clears my file and replacing the find string in file.
#!/usr/bin/python
open('vpc.xml','r+') as p: #open a file in read and write mode
p=rp.readlines()
print p #printing what content read by p
for line in p: #for loop up to end of line in file
if "<mac address=" in line: #if condition encounter by for loop line then it replaces the string specified in if condition.
print line
r.write(line.replace("<mac address=","<mac address1="))
elif "<source bridge=" in line:
print line
r.write(line.replace("<source bridge=","<source bridge1="))
elif "<target dev" in line:
print line
r.write(line.replace("<target dev","<target dev1"))
else :
print 'no changes'
continue
#!/usr/bin/python
o = input("enter how many vpcs")
y = input("enter how many eth interfaces")
for k in range(1,o):
h='vpc'+str(k)+'.xml'
print h
#j = input("enter how many eth interfaces")
ri=open(h,'r')
line = ri.read()
ri.close()
for i in range(0,y)
for s in range(i+1)
dev_val={'network':'bridge','<man':'<manneth0','<man':'vpc'+str(i)+_eth+str(i),}
for key,val in dev_val.items():
line = line.replace(key,val)
print line
with open(h,'w') as v:
v.write(line)
v.close()

Categories