Writing before specific line python - python

i have this piece of code:
asm = open(infile)
asmw = open(outfile, "w")
shutil.copyfile(infile, outfile)
for x in range(0, 8):
xorreg.append("xor " + reg[x] + ", " + reg[x])
for line in asm:
if any(s in line for s in xorreg):
found += line.count(xorreg[x])
print line
i want to write some text lines in the file right before "line" (the one printed)
how can i do that?
Thanks

This script appends to every lien containing the string Gandalf a new string The greatest wizard of all times was:
# show what's in the file
with open("some_file.txt", 'r') as f:
print f.read()
new_content = []
with open("some_file.txt", "r") as asmr:
for line in asmr.readlines():
if "Gandalf" in line:
# we have a match,we want something but we before that...
new_content += "The greatest wizard of all times was:"
new_content += line
# write the file with the new content
with open("some_file.txt", "w") as asmw:
asmw.writelines(new_content)
# show what's in the file now
with open("some_file.txt", 'r') as f:
print f.read()

Related

IndexError: list index out of range - PythonError

I'm creating a program that should create a file (.txt) based on each line of 'clouds.txt'. This is my code:
def CreateFile():
global file_name
f = open(file_name,"w+")
f.write(list_email + ":")
f.close()
def WriteInConfig():
f = open("config/config.txt","a")
f.write(list_name + "\n")
f.close()
with open("clouds.txt","r") as f:
list_lines = sum(1 for line in open('clouds.txt'))
lines = f.readline()
for line in lines:
first_line = f.readline().strip()
list_email = first_line.split('|')[1] #email
print("Email: " + list_email)
list_pass = first_line.split('|')[2] #pass
print("Pass: " + list_pass)
list_name = first_line.split('|')[3] #name
print(list_name)
global file_name
file_name = "config/." + list_name + ".txt"
with open('clouds.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('clouds.txt', 'w') as fout:
fout.writelines(data[1:])
CreateFile()
WriteInConfig()
The clouds.txt file looks like this:
>|clouds.n1c0+mega01#gmail.com|cwSHklDIybllCD1OD4M|Mega01|15|39.91|FdUkLiW0ThDeDkSlqRThMQ| |x
|clouds.n1c0+mega02#gmail.com|tNFVlux4ALC|Mega02|50|49.05|lq1cTyp13Bh9-hc6cZp1RQ|xxx|x
|clouds.n1c0+mega03#gmail.com|7fe4196A4CUT3V|Mega03|50|49.94|BzW7NOGmfhQ01cy9dAdlmg|xxx|xxx >
Everything works fine until 'Mega48'. There I get "IndexError: list index out of range"
>|clouds.n1c0+mega47#gmail.com|bd61t9zxcuC1Yx|Mega47|50|10|Xjff6C8mzEqpa3VcaalUuA|xxx|x
|clouds.n1c0+mega48#gmail.com|kBdnyB6i0PUyUb|Mega48|50|0|R6YfuGP2hvE-uds0ylbQtQ|xxx|x
|clouds.n1c0+mega49#gmail.com|OcAdgpS4tmSLTO|Mega49|50|28.65|xxx| >
I checked and there are no spaces/other characters. As you could see, after creating the file, the program deletes the line. After the error, if I'm starting the program again (and starts from 'Mega47') it doesn't show the error, and everything works as planned.
Any ideas how to fix this?
I see many mistakes in your code. First, what do you want with this list_lines = sum(1 for line in open('clouds.txt'))?
You have a problem in your for loop because you did lines = f.readline() so lines is the first line, then you do for line in lines where line will be each character of the first line and there are more character in the first line than lines in your file to read.
[edited]
you don't need to know the number of lines in the file to do a for loop. You can just do for line in f:, then you don't need to read the line again with readline it is already in the variable line

How to read line in text file and replace the whole line in Python?

I want to replace a whole line in a text document, if there is a line that begins with "truck_placement"
Can I remove the whole line when it contains "truck_placement" and then write the new text?
I tried it but it only inserts the new text und doesn't replace the whole line.
Thats the current code:
cordget = coordinatesentry.get()
fin = open(save_file,"r")
filedata = fin.read()
fin.close
newdata = filedata.replace("truck_placement: " , "truck_placement: " + cordget)
fin = open(save_file, "w")
fin.write(newdata)
fin.close
Your best bet is to append all the lines without "truck_placement" to a new file. This can be done with the following code:
original = open("truck.txt","r")
new = open("new_truck.txt","a")
for line in original:
if "truck_placement" not in line:
new.write(line)
original.close()
new.close()
You can either read the whole file into one string and replace the line using regular expression:
import re
cordget = "(value, one) (value, two)"
save_file = "sample.txt"
with open(save_file, "r") as f:
data = f.read()
# Catch the line from "truck_placement: " until the newline character ('\n')
# and replace it with the second argument, where '\1' the catched group
# "truck_placement: " is.
data = re.sub(r'(truck_placement: ).*\n', r'\1%s\n' % cordget, data)
with open(save_file, "w") as f:
f.writelines(data)
Or you could read the file as a list of all lines and overwrite the specific line:
cordget = "(value, one) (value, two)"
save_file = "sample.txt"
with open(save_file, "r") as f:
data = f.readlines()
for index, line in enumerate(data):
if "truck_placement" in line:
data[index] = f"truck_placement: {cordget}\n"
with open(save_file, "w") as f:
f.writelines(data)

Delete a certain line in text file if user input string matches

If that string input by User exists in text file, the program should find/return line number in text file and print the line number
kw is the user input btw
some code for reference:
def DELITEM():
kw = Dele.get()
with open('notify.txt') as f:
if kw in f.read:
print('the number of the line kw is in')
I guess you could do something like:
with open('notify.txt', 'r') as f:
for num, line in enumerate(f):
if kw==line:
print(num)
Here enumerate() adds a counter to the file that allows you to identify lines.
you could loop through the lines until you find it with readlines
DELITEM():
kw = Dele.get()
with open('notify.txt', 'r') as f:
if kw in f.read:
lines = f.readlines()
for i in range(len(lines)):
if kw in lines[i]:
print("The line is",i)
break
To delete the line from the text file, on way would be to delete the line in the list then write the lines back onto the file. So something like this
del lines[i]
then have another with where you write
with open('notify.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
so putting this altogether you have
DELITEM():
lines = []
kw = Dele.get()
with open('notify.txt', 'r') as f:
if kw in f.read:
lines = f.readlines()
for i in range(len(lines)):
if kw in lines[i]:
print("The line is",i)
del lines[i]
break
with open('notify.txt', 'w') as f:
for line in lines:
f.write(line + '\n')

python text file parse and print

I have a text file with 300 lines.
I am looking for a word "ABC" in each line
If this word is found i want to print the line before it was found and then the next X lines.
This is the code i have so far but i don't know how to print based on given problem statement.
path = ('C:\\Users\\40081\\PycharmProjects\\datalog_parsing')
count2=1
count1=1
num_lines = open('BBCnt123.txt').read().count('\n')
print (num_lines)
count2=count1
while count2<=num_lines:
file_name = open("BBCnt123.txt", 'r+')
f= open('BBCnt1234' + '.txt', 'w+')
for line_no, line in enumerate (file_name):
line=f.readlines()
if "BBCnt" in line:
f.writelines((line[count2-1]) )
count2= count2+1
file_name.close()
f.close()
with open("file.txt","r") as f:
lines=f.readlines()
[print(lines[c-1]+lines[c:c+X]) for c,e in enumerate(lines) if "ABC" in e]
Try this list comprehension

Deleting a complete line if an entry in the line is not present a list

I am trying to parse every line in list.txt and if any of the change(number) is not present in change_list, delete that whole entry (not just that number) and create an new file OUTPUT.txt with the remaining numbers.
In the below example 350166 is not present in change_list, so the whole line "350882 348521 350166" is removed and only the remaining ones are added to output.txt.
For some reason I dont seem to get the desired outupt. Can anyone point where is it going wrong?
change_list=[]
def changecheck(change) :
changelist=['355199','352470','346917','350882','348521']
if change in changelist:
return 1
else:
return 0
with open('list.txt', 'r') as f:
for line in f :
line=line.strip()
change_line = line
print "change_line"
print change_line
for element in change_line:
change_list = element.split(' ')
for changeid in change_list:
print "changeid"
print changeid
returnVal = changecheck('changeId')
if returnVal == 1:
#write the whole line to a new file
with open('output.txt', 'r') as f:
f.writelines(element)
files:
list.txt
350882 348521 350166
346917 352470
355199
OUTPUT.txt
346917 352470
355199
Make your changecheck a set, and then build a generator over the input splitting it up into separate numbers, and only include lines in the file where all numbers on the line are in the changecheck..., eg:
changelist = {'355199','352470','346917','350882','348521'}
with open('input') as fin, open('output', 'w') as fout:
lines = (line.split() for line in fin)
valid = (' '.join(line) + '\n' for line in lines if all(el in changelist for el in line))
fout.writelines(valid)

Categories

Resources