Beginner Python: Reading and Writing to the Same File

Beginner Python: Reading and writing to the same file

Updated Response:

This seems like a bug specific to Windows - http://bugs.python.org/issue1521491.

Quoting from the workaround explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html

the effect of mixing reads with writes on a file open for update is
entirely undefined unless a file-positioning operation occurs between
them (for example, a seek()). I can't guess what
you expect to happen, but seems most likely that what you
intend could be obtained reliably by inserting

fp.seek(fp.tell())

between read() and your write().

My original response demonstrates how reading/writing on the same file opened for appending works. It is apparently not true if you are using Windows.

Original Response:

In 'r+' mode, using write method will write the string object to the file based on where the pointer is. In your case, it will append the string "Test abc" to the start of the file. See an example below:

>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\n'
>>> f.write("foooooooooooooo")
>>> f.close()
>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\nfoooooooooooooo'

The string "foooooooooooooo" got appended at the end of the file since the pointer was already at the end of the file.

Are you on a system that differentiates between binary and text files? You might want to use 'rb+' as a mode in that case.

Append 'b' to the mode to open the file in binary mode, on systems
that differentiate between binary and text files; on systems that
don’t have this distinction, adding the 'b' has no effect.
http://docs.python.org/2/library/functions.html#open

Reading and writing to the same file from two different scripts at the same time

Technically the scripts won't run at the same time, so no issue will occur, unless of course you run them from separate threads, in which case I think it's fine.

But you can put the script into a function and call them in the loop as you can pass the assigned variable into that function, this is shown by Joshua's answer showing you can loop into a file at the same time.

But if you want to keep them at separate files they won't be called at the same time, because if you call them from a file they won't run at the very same tick, even if you were too it would be fine.

writing back into the same file after reading from the file

Use a temporary file. Python provides facilities for creating temporary files in a secure manner. Call example below with: python modify.py target_filename

 import tempfile
import sys

def modify_file(filename):

#Create temporary file read/write
t = tempfile.NamedTemporaryFile(mode="r+")

#Open input file read-only
i = open(filename, 'r')

#Copy input file to temporary file, modifying as we go
for line in i:
t.write(line.rstrip()+"\n")

i.close() #Close input file

t.seek(0) #Rewind temporary file to beginning

o = open(filename, "w") #Reopen input file writable

#Overwriting original file with temporary file contents
for line in t:
o.write(line)

t.close() #Close temporary file, will cause it to be deleted

if __name__ == "__main__":
modify_file(sys.argv[1])

References here:
http://docs.python.org/2/library/tempfile.html

How to read text file in python after that write something on same file

This code may help you.

with open('result.txt','r') as file:
data = file.readlines() # return list of all the lines in the text file.

for a in range(len(data)): # loop through all the lines.
line = data[a]
if 'person' in line and 'tv' in line: # Check if person and tv in the same line.
data[a] = line.replace('\n','') + ' status : High\n'
elif 'person' in line and 'laptop' in line:# Check if person and laptop in the same line.
data[a] = line + ' status : Low\n'

with open('result.txt','w') as file:
file.writelines(data) # write lines to the file.

How to read and write a text file in the same time in python?

You can try the following, the problem at the moment is that you are only storing and writing the final occurrence of the modified line, instead it's better to create a copy of the modified file in memory and then writing out (see below)

remove_commas = re.compile("House")
answer = {}

with open("\DEMO_houses.txt", "r") as inp:
new_file_lines = []
for line in inp:
if remove_commas.match(line):
line = line.replace(',', '')
new_file_lines.append(line)

with open("DEMO_houses.txt", "w") as document1:
document1.writelines(new_file_lines)

Two processes reading/writing to the same file Python

test1.py

import os
f = open('txt.txt', 'a', os.O_NONBLOCK)
while 1:
f.write('asd')
f.flush()

test2.py

import os
f = open('txt.txt', 'r', os.O_NONBLOCK)
while 1:
print f.read(3)

This works fine for me.



Related Topics



Leave a reply



Submit