Rajeev
Rajeev

Reputation: 46929

python search and write to file

In the below code i am trying to replace the contents of a file which has the following content in it. hellohello world and the string hellohello should be replaced by hello and be wrote back to the file.Ho to go about this

  #!/usr/bin/python
  import os

  new_file_list=[]
  all_files=os.listdir("/tmp")
  for ff in all_files:
     if ff.endswith(".txt"):
        new_file_list.append(ff)

  for files in new_file_list:
     if files == "a.txt":
       print "======================================="
       file_name="/tmp/"+str(files)
       print file_name
       f=open(file_name ,"rw")
       while True:
         print "======================================="
         for line in f.readline():
            print line
            print "======================================="
            f.write(line.replace("hellohello","hello"))
            print line
         else:
            break
       for line in f.readline():
         print line

  f.close()

Upvotes: 2

Views: 1818

Answers (5)

Mariusz Jamro
Mariusz Jamro

Reputation: 31653

You can use fileinput module to replace string in a file in place (without opening two files or opening the same file twice or loading entire text file into memory in your code).

#!/usr/bin/python
import os
import fileinput

new_file_list=[]
all_files=os.listdir("/tmp")
for ff in all_files:
 if ff.endswith(".txt"):
    new_file_list.append(ff)

for files in new_file_list:
 print files
 if files == "a.txt":
   print "======================================="
   file_name="/tmp/"+str(files)
   print file_name

   f = fileinput.FileInput(file_name, inplace=1)

   print "======================================="
   for line in f:
        line = line.replace("hellohello","hello")
        print line,
   f.close()

Upvotes: 2

Rik Poggi
Rik Poggi

Reputation: 29302

An alternative to read the whole file and then write back your text, can be to use a temp file.

You can write line by line to a temporary file while you read and at the end replace your orignal file with the temp one:

import shutil

filename = 'a.txt'
temp = 'copy.tmp'
with open(filename, 'r') as input_file, open(temp, 'w') as output_file:
    for line in input_file:
        output_file.write(line.replace('hellohello','hello'))

shutil.move(temp, filename)

Upvotes: 0

Bogdan
Bogdan

Reputation: 8246

You should really work on improving you code imo. First when working with files I recommend using the os module whereever possible instead of using string concatenation.

So instead of: file_name="/tmp/"+str(files) you could do os.path.join('/tmp', files). You can also get the file extension with name, extension = os.path.splitext(ff) and the you can test if the extension is what you need.

Also from an algorithmical point of view I don't see why you iterate over all the files in the directory, put them in a list, then iterate over that list again to do the processing. You could just as well do:

   for ff in os.listdir('/tmp'):
       if os.path.splitext(ff)[1] == ".txt":
           file_n = os.path.join('/tmp', ff)
           with open(file_n, 'r') as file_p:
               text = file_p.read().replace('hellohello world', 'hello world')
           with open(file_n, 'w') as file_p:
               file_p.write(text)

And that should be pretty much all you need.

Upvotes: 0

Caspar
Caspar

Reputation: 7759

The easiest way to go for a simple task such as this is to read all the data from the file, perform the substitution, and then write the new data to the file.

Here is some sample code for what you appear to be trying to do:

filename = "/tmp/a.txt"
with open(filename, 'r') as f:
  data = f.read()
with open(filename, 'w') as f:
  f.write(data.replace("hellohello", "hello"))

Upvotes: 1

Zach Kelling
Zach Kelling

Reputation: 53829

You can't write to the middle of a file. The easiest solution would be to read the file into memory, replace the text and then write it back out.

with open('file_name') as f:
    text = f.read()

text = text.replace('hellohello', 'hello')

with open('file_name', 'w') as f:
    f.write(text)

Upvotes: 1

Related Questions