How to replace all occurrence of a string in file except the first occurrence using Python? - python-3.x

Here is the content of my file
I want to replace all occurrence of pyt_batch_id with any number but not the first occurrence.
I tried the below method and it is working as expected but I don't think this the best approach.
s = open("BATCH_ROLLBACK.txt").read()
s = s.replace('pyt_batch_id', '123456')
f = open("BATCH_ROLLBACK.txt", 'w')
f.write(s)
f.close()
f2 = open('BATCH_ROLLBACK.txt', 'r')
contents = f2.read().replace('123456', 'pyt_batch_id',1)
f2.close()
f2 = open('BATCH_ROLLBACK.txt', 'w')
f2.write(contents)
f2.close()
output :-
Could anyone please suggest other alternative methods?
Found similar question but that is for a line not for file.
How to replace all occurences except the first one?

Related

extract words from a text file and print netxt line

sample input
in parsing a text file .txt = ["'blah.txt'", "'blah1.txt'", "'blah2.txt'" ]
the expected output in another text file out_path.txt
blah.txt
blah1.txt
blah2.txt
Code that I tried, this just appends "[]" to the input file. While I also tried perl one liner replacing double and single quotes.
read_out_fh = open('out_path.txt',"r")
for line in read_out_fh:
for word in line.split():
curr_line = re.findall(r'"(\[^"]*)"', '\n')
print(curr_line)
this happens because while you reading a file it will be taken as string and not as a list even if u kept the formatting of a list. thats why you getting [] while doing re.for line in read_in_fh: here you are taking each letters in the string thats why you are not getting the desired output. so iwrote something first to transform the string into a list. while doing that i also eliminated "" and '' as you mensioned. then wrote it in to a new file example.txt.
Note: change the file name according to your files
read_out_fh = open('file.txt',"r")
for line in read_out_fh:
line=line.strip("[]").replace('"','').replace("'",'').split(", ")
with open("example.txt", "w") as output:
for word in line:
#print(word)
output.write(word+'\n')
example.txt(outputfile)
blah.txt
blah1.txt
blah2.txt
The code below works out for your example you gave in the question:
# Content of textfile.txt:
asdasdasd=["'blah.txt'", "'blah1.txt'", "'blah2.txt'"]asdasdasd
# Code:
import re
read_in_fh = open('textfile.txt',"r")
write_out_fh = open('out_path.txt', "w")
for line in read_in_fh:
find_list = re.findall(r'\[(".*?"*)\]', line)
for element in find_list[0].split(","):
element_formatted = element.replace('"','').replace("'","").strip()
write_out_fh.write(element_formatted + "\n")
write_out_fh.close()

Python3 reading text file with 6 values divided by a comma in each line and listing line

Suppose i have a file.txt, in each line of it 6 value divided by a comma.
a,b,c,d,e,f
How can I list each line in the form of [a,b,c,d,e,f]?
i would suggest using .split(), as it can split it like this:
f = open("file.txt", "r")
f.read()
spited = f.split(",")
print(spited)
Which prints the numbers/letters as a list.
If you have any questions on why/how this works, just ask!! :D
Thanks for your tips, ive finally managed to do what i wanted with this piece of code:
with open(l, "r") as f:
for line in f:
inner_list = [elt.strip() for elt in line.split(',')]

Python : Updating multiple words in a text file based on text in another text file using in_place module

I have a text file say storyfile.txt
Content in storyfile.txt is as
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe
I have another file- hashfile.txt that contains some words separated by comma(,)
Content of hashfile.txt is:
All,mimsy,were,the,borogoves,raths,outgrabe
My objective
My objective is to
1. Read hashfile.txt
2. Insert Hashtag on each of the comma separated word
3. Read storyfile.txt . Search for same words as in hashtag.txt and add hashtag on these words.
4. Update storyfile.txt with words that are hash-tagged
My Python code so far
import in_place
hashfile = open('hashfile.txt', 'w+')
n1 = hashfile.read().rstrip('\n')
print(n1)
checkWords = n1.split(',')
print(checkWords)
repWords = ["#"+i for i in checkWords]
print(repWords)
hashfile.close()
with in_place.InPlace('storyfile.txt') as file:
for line in file:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
file.write(line)
The output
can be seen here
https://dpaste.de/Yp35
Why is this kind of output is coming?
Why the last sentence has no newlines in it?
Where I am wrong?
The output
attached image
The current working code for single text
import in_place
with in_place.InPlace('somefile.txt') as file:
for line in file:
line = line.replace('mome', 'testZ')
file.write(line)
Look if this helps. This fulfills the objective that you mentioned, though I have not used the in_place module.
hash_list = []
with open("hashfile.txt", 'r') as f:
for i in f.readlines():
for j in i.split(","):
hash_list.append(j.strip())
with open("storyfile.txt", "r") as f:
for i in f.readlines():
for j in hash_list:
i = i.replace(j, "#"+j)
print(i)
Let me know if you require further clarification on the same.

Can anyone help to fecth only dictionary format data from a file(example of data shown below)

Here is the how the file is setup:
Some lines written here.
Line one written here.
line two written here.
key1:value1
key2:value2
key3:value3
key4:value4
All above keys and values are mentioned. Then:
Line three written here.
key5:value5 key6:value6
key7:value7
I have tried this way but did not get the desired result..
with open(r'/home/rajat/PycharmProjects/MyProject/testfile.txt') as f:
lines = f.readlines()
regex = re.compile(r'''
[\S]+:
(?:
\s
(?!\S+:)\S+
)+
''', re.VERBOSE)
matches = regex.findall(str(lines))
for match in matches:
print(match)
Finally I got it what i wanted by myself...
Exact code below for my solution.
import re
with open(r'/home/coding_learner/PycharmProjects/MyProject/testfile.txt', 'r') as f:
lines = f.readlines()
lines = map(lambda s: s.strip(), lines)
r = re.compile(".[\S]+: [\S]+")
newlist = list(filter(r.match, lines))
print(newlist)

How do I replace the 4th item in a list that is in a file that starts with a particular string?

I need to search for a name in a file and in the line starting with that name, I need to replace the fourth item in the list that is separated my commas. I have began trying to program this with the following code, but I have not got it to work.
with open("SampleFile.txt", "r") as f:
newline=[]
for word in f.line():
newline.append(word.replace(str(String1), str(String2)))
with open("SampleFile.txt", "w") as f:
for line in newline :
f.writelines(line)
#this piece of code replaced every occurence of String1 with String 2
f = open("SampleFile.txt", "r")
for line in f:
if line.startswith(Name):
if line.contains(String1):
newline = line.replace(str(String1), str(String2))
#this came up with a syntax error
You could give some dummy data which would help people to answer your question. I suppose you to backup your data: You can save the edited data to a new file or you can backup the old file to a backup folder before working on the data (think about using "from shutil import copyfile" and then "copyfile(src, dst)"). Otherwise by making a mistake you could easily ruin your data without being able to easily restore them.
You can't replace the string with "newline = line.replace(str(String1), str(String2))"! Think about "strong" as your search term and a line like "Armstrong,Paul,strong,44" - if you replace "strong" with "weak" you would get "Armweak,Paul,weak,44".
I hope the following code helps you:
filename = "SampleFile.txt"
filename_new = filename.replace(".", "_new.")
search_term = "Smith"
with open(filename) as src, open(filename_new, 'w') as dst:
for line in src:
if line.startswith(search_term):
items = line.split(",")
items[4-1] = items[4-1].replace("old", "new")
line = ",".join(items)
dst.write(line)
If you work with a csv-file you should have a look at the csv module.
PS My files contain the following data (the filenames are not in the files!!!):
SampleFile.txt SampleFile_new.txt
Adams,George,m,old,34 Adams,George,m,old,34
Adams,Tracy,f,old,32 Adams,Tracy,f,old,32
Smith,John,m,old,53 Smith,John,m,new,53
Man,Emily,w,old,44 Man,Emily,w,old,44

Resources