How to edit a line in a notepad file using python - python-3.x

I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?
#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()
#(This was my second attempt)
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()

you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src to a variable data line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info\n'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open with r+):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info\n'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)

You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.
f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()
Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')
f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
if i == Which_Line:
f.writelines(str(Edit)+"\n")
else:
f.writelines(line)
f.close()

Related

search and replace using a file for computer name

I've got to search for the computer name and replace this with another name in python. These are stored in a file seperated by a space.
xerox fj1336
mongodb gocv1344
ec2-hab-223 telephone24
I know this can be done in linux using a simple while loop.
What I've tried is
#input file
fin = open("comp_name.txt", "rt")
#output file to write the result to
fout = open("comp_name.txt", "wt")
#for each line in the input file
for line in fin:
#read replace the string and write to output file
fout.write(line.replace('xerox ', 'fj1336'))
#close input and output files
fin.close()
fout.close()
But the output don't really work and if it did it would only replace the one line.
u can try this way:
with open('comp_name.txt', 'r+') as file:
content = file.readlines()
for i, line in enumerate(content):
content[i] = line.replace('xerox', 'fj1336')
file.seek(0)
print(str(content))
file.writelines(content)

Deleting from files

(I have only been learning Python3 for about 2 weeks now. So if you could keep the answer as ELI5 as possible that would be great)
In this image, I have first read the file and then second zeroed the file and recreated it while removing all the lines containing 'Ford'
This image shows the contents of the file that I wish to be printed out
The problem I have is that the result is being printed as 'none'.
How would I make it so this program prints out what is inside the file?
Thanks!
code below
def delete_ford(path, term):
buffer = []
with open(path, "r") as file:
for line in file:
buffer.append(line.strip())
with open(path, "w") as file:
for line in buffer:
if line != term:
file.write(line + "\n")
with open(path, "r") as file:
for line in file:
buffer.append(line.strip())
print(buffer)
print(delete_ford("cars.txt", "Ford"))
As #John Zwinck and #Albert Alberto pointed out, your function has nothing to return as the output is written to the file.
If you want it simply to print out the contents of the file, you can do this when you're writing to it like this:
with open(path, "w") as file:
for line in buffer:
if line != term:
file.write(line + "\n") # This is what is being written to the file
print(line) # So this will effectively output the contents of the file
Hope this does what you want it to

Find string and replace line

I already could get a lot of my code together (although it is not a long code). However i am struggeling to achieve the "replace the whole line and not only the search term". Is there like a symbol you can place to do that? Like: * or % etc.
import glob
for files in glob.glob("./prtr/*p*"):
with open(files, 'r') as file:
filedata = file.read()
filedata = filedata.replace('TCPOPTS', 'TCPOPTS = 80\n')
with open(files, 'w') as file:
file.write(filedata)
It works so far that "TCPOPTS" is replaced with "TCPOPTS = 80" and a linebreak is done. But it is not deleting the rest of that line but just moves it to the next line. Which is of course correct due the code. So as mentioned all i need now is to have it not replace the search term but the whole line containing that search term.
Any advice is highly apreciated :)
Kind regards
Edit:
Before:
TCPOPTS = 90
Afterwards:
TCPOPTS = 80
= 90
Expected:
TCPOPTS = 80
I recently solved a very similar task in the following way:
# Scan file
with open(filePath, 'r') as file:
fileContent = file.readlines()
# Find line, where modification should be done
for lineIndex in range(len(fileContent)):
if ('TCPOPTS' in fileContent[lineIndex]):
fileContent[lineIndex] = 'TCPOPTS = 80\n'
with open(filePath, 'w') as tableFile:
tableFile.writelines(fileContent)
break
The benefit of doing it this way is, that the file is not rewritten, if your keyword is not found.
Try using str.startswith
Ex:
import glob
for files in glob.glob("./prtr/*p*"):
res = []
with open(files) as infile:
for line in infile: #Iterate Each line
if line.startswith("TCPOPTS"): #Check if TCPOPTS in line
res.append("TCPOPTS = 80\n")
else:
res.append(line)
with open(files, "w") as outfile: #Write back to file.
for line in res:
outfile.write(line)
You can use re.sub (after importing re) to match the whole line and use back-references to preserve selective portions of the match:
Change:
filedata = filedata.replace('TCPOPTS', 'TCPOPTS = 80\n')
to:
filedata = re.sub(r'^(?P<header>TCPOPTS\s*=\s*).*', r'\g<header>80', filedata, flags=re.MULTILINE)

How do I copy part of a file to a new file?

In Python I'd like to open a text file as file, and copy only part of the file to a new file. For example, I want to copy only part of the file, say between the line EXAMPLE\n and line END\n. So I want to delete everything before line EXAMPLE\n and everything after line END\n. How can I do that?
I can read the file using the following code, but how do I delete the
with open(r'filepath\myfile.txt', 'r') as f:
file = f.readlines()
<delete unwanted lines in file>
with open(r'filepath\newfile.txt', 'r') as f:
f.writelines(file)
Create a new array and only add the lines you want to that array:
new_lines = []
found_example=False
found_end=False
for line in file:
if line == "EXAMPLE\n": found_example=True
if line == "END\n": found_end=True
if found_example != found_end: new_lines.append(line)
file = new_lines
Now just write file to your file and you are done. Note that in your example you didn't open the file in write mode, so it would look more like this:
with open(r'filepath\newfile.txt', 'w+') as f:
f.writelines(file)
Read each line and notice whether it contains EXAMPLE or END. In the former case, set a flag to start outputting lines; in the latter, set the same flag to stop.
process = False
with open('myfile.txt') as f, open('newfile.txt', 'w') as g:
for line in f:
if line == 'EXAMPLE\n':
process = True
elif line == 'END\n':
process = False
else:
pass
if process:
line = line.strip()
print (line, file=g)

reading text line by line in python 3.6

I have date.txt file where are codes
ex:
1111111111111111
2222222222222222
3333333333333333
4444444444444444
I want to check each code in website.
i tried:
with open('date.txt', 'r') as f:
data = f.readlines()
for line in data:
words = line.split()
send_keys(words)
But this copy only last line to.
I need to make a loop that will be checking line by line until check all
thanks for help
4am is to late 4my little brain..
==
edit:
slove
while lines > 0:
lines = lines - 1
with open('date.txt', 'r') as f:
data = f.readlines()
words = data[lines]
print(words)
Try this I think it will work :
line_1 = file.readline()
line_2 = file.readline()
repeat this for how many lines you would like to read.
One thing to keep in mind is if you print these lines they will all print on the same line.

Resources