search and replace using a file for computer name - python-3.x

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)

Related

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

How to I check whether a file already contains the text I want to append?

I am currently working on a project. So I want to read all the *.pdf files in a directory, extract their text and append it to a text file. So far so good. I was able to do this, yeah.
Now the problem: if I am reading the same directory again, it appends the same files again. Is there a way to check whether the extracted text is already in the file and thus, skip the whole thing?
My code for this looks like this right now (I created the directory variable already):
`
for filename in os.listdir(directory):
if filename.endswith(".pdf"):
file = os.path.join(directory, filename)
print(file)
#parse data from file
file_data = parser.from_file(file)
#get files text content
text = file_data['content']
#print(type(text))
print("len ", len(text))
#print(text)
#save to textfile
f = open("test2.txt", "a+", encoding = 'utf-8')
f.write(text)
f.close()
else:
continue
`
Thanks in advance!
One thing you could do is load the file contents and check if the file is within the file:
if text in open("test2.txt"):
# write here
else:
# text is already in file, don't write
However, this is very inefficient. A better way is to create a file with the filenames that you have already written, and check that:
(at the beginning of your code):
files = open("files.txt").readlines()
(before parser.from_file(file)):
if file in files:
continue # don't read or write
(after f.close()):
files.append(file)
(after the whole loop has finished)
with open("files.txt", "w") as f:
f.write("\n".join(files))
Putting it all together:
files = open("files.txt").readlines()
for filename in os.listdir(directory):
if filename.endswith(".pdf"):
file = os.path.join(directory, filename)
if file in files:
continue # don't read or write
print(file)
#parse data from file
file_data = parser.from_file(file)
#get files text content
text = file_data['content']
#print(type(text))
print("len ", len(text))
#print(text)
#save to textfile
f = open("test2.txt", "a+", encoding = 'utf-8')
f.write(text)
f.close()
files.append(file)
else:
continue
with open("files.txt", "a+") as f:
f.write("\n".join(files))
Note that you need to create a file named files.txt in the current directory.

How to edit a line in a notepad file using python

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()

How to replace all instances of a string in text file with Python 3?

I am trying to replace all instances of a given string in a text file. I am trying to read the file line by line and then use the replace function, however it is just outputting a blank file instead of the expected. What could I be doing wrong?
file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")
fopen = open(file, 'r+')
lines = []
for line in fopen:
line = line.replace(remove,"")
fopen.close()
Try this:
# Make sure this is the valid path to your file
file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")
# Read in the file
with open(file, "r") as file:
filedata = file.read()
# Replace the target string
filedata = filedata.replace(remove, "")
# Write the file out again
with open(file, "w") as file:
file.write(filedata)
Note: You might want to use with open syntax, the benefit is elaborated in this answer by Jason Sundram.

How do I delete line starting with ">" while reading a file to string in Python

I want to read all files ending with ".fasta" in mydir directory one by one and save content except lines starting with ">" to a string called "data" for further analysis while also ignoring newline characters. So far I have this:
for file in os.listdir(mydir):
if file.endswith(".fasta"):
with open(file, 'r') as myfile:
data = myfile.read().replace('\n', '')
How do I read file into a string AND in the same command skip all lines starting with ">"?
Here you go
for file in os.listdir(mydir):
if file.endswith(".fasta"):
with open(file, 'r') as myfile:
data = "".join(line for line in myfile if line[:1]!='>')

Resources