Why read operation isn't working in this code? - python

I am learning python file operations and was experimenting with different options to read and write.
As far as I know this code should be able to both append and read from test.txt file as I have opened it with "a+". But though the append operation is working as expected, I am not getting any output from the print function.
my_file = open('test.txt', 'a+')
my_file.write("You know nothin' Jon Snow.")
content = my_file.read()
print(content)
my_file.close()
What I'm doing wrong here?

When you first open the file, the file pointer is at the end of the file. The write leaves the file pointer following the new text. When you try to read, there's nothing left to read; you are already at the end of the file. If you wanted to read the entire contents of the file, you would need to seek to the beginning before reading.
with open('test.txt', 'a+') as my_file:
my_file.write("You know nothin' Jon Snow.")
my_file.seek(0)
content = my_file.read()
print(content)

Because after you do the write you are now positioned at the end of the file so when you do a read operation there is nothing to read. You need to do first do a seek to position yourself somewhere before the end of file:
my_file = open('test.txt', 'a+')
my_file.write("You know nothin' Jon Snow.")
my_file.seek(0)
content = my_file.read()
print(content)
my_file.close()

Related

How to read a file and write it entirely to several text files using Python?

I want to load/read a text file and write it to two other text files "entirely". I will write other different data to the following of these two files later.
The problem is that the loaded file is only written to the first file, and no data from that loaded file is written to the second file.
The code I am using:
fin = open("File_Read", 'r')
fout1 = open("File_Write1", 'w')
fout2 = open("File_Write2", 'w')
fout1.write(fin.read())
fout2.write(fin.read()) #Nothing is written here!
fin.close()
fout1.close()
fout2.close()
What is happening and what is the solution?
I prefer using open instead of with open.
Thanks.
Apparently the fin.read() reads all the lines, the next fin.read() will continue from where the previous .read() ended (which is the last line). To solve this, I would simply go for:
text_fin = fin.read()
fout1.write(text_fin)
fout2.write(text_fin)
fin = open("test.txt", 'r')
data = fin.read()
fin.close()
fout1 = open("test2.txt", 'w')
fout1.write(data)
fout1.close()
fout2 = open("test3.txt", 'w')
fout2.write(data)
fout2.close()
N.B. with open is the safest and best way but at least you need to close the file as soon as there are not needed anymore.
You can try iterating through your original file line by line and appending it to both the files. You are running into the problem because file.write() method takes string argument.
fin = open("File_Read",'r')
fout1 = open("File_Write1",'a') #append permissions for line-by-line writing
fout2 = open("File_Write2",'a') #append permissions for line-by-line writing
for lines in fin:
fout1.write(lines)
fout2.write(lines)
fin.close()
fout1.close()
fout2.close()
*** NOTE: Not the most efficient solution.

Trying to open and read a file in python but it creates and opens an empty file

I am trying to open several csv files in python using this code:
file= open('file.csv', "r")
contents= file.read()
allLines = file.readlines()
print(contents)
print(allLines)
But all python prints is "[]"
When I look in the folder for my python project- the file is there but it is now empty- what's going wrong?
With regards to why python is printing an empty array, I'm assuming that you only experience this when printing allLines . When using read operations on file that you've left open, Python leaves the read cursor at the end of the file. I believe if you use seek(0) you can return the read cursor back to the beginning of the file. i.e.:
file = open('file.csv', 'r')
contents = file.read()
file.seek(0)
allLines = file.readlines()
print(contents)
print(allLines)
This seems rather unusual that it would be removing your data since it is only reading. You shold try providing the full path to the file.

File cannot be read after regex operation (Python)

I am trying out regex operations in Python. However, I am not able to read the file again once I use it for the same.
f = codecs.open(filename, 'rU', 'utf-8')
#print f.read() works here
#printing the year
year = re.search(r'Popularity in (\w+)',f.read())
print year.group(1)
#now, this returns nothing !
print f.read()
I am not able to understand what I am doing wrong here.
When calling f.read(), the file object will step over all lines and as file objects are generators, it will remember where it stopped reading. If you continue reading with calling f.read() again, the file object will continue reading where it left, i.e. at the end of the file. By calling f.seek(0) you will reset the position in the file and you can read the file again. In your case it may make more sense to save the content of the file in variable, which can be accessed multiple times.
file_content = f.read()
year = re.search(r'Popularity in (\w+)', file_content)
print year.group(1)
print file_content
or
year = re.search(r'Popularity in (\w+)', f.read())
print year.group(1)
f.seek(0) # reset the file read position
print f.read()
I would choose the first option.
Add f.seek(0) before the second read. Once the file was readed completely, the pointer comes to the file end. Now you have to move the pointer up(ie, file start) . In-order to do this, we have to add fileobject.seek(0)

Not writing to file, even with f.close()

Edited my program - still having same issue
Also, the linked answer that was recommened is useless as it only tells you that you cannot modify a file in place and does not offer any good solution.
I have a file that has line numbers at the start of it. I wrote a python script to eliminate these line numbers. This is my second attempt at it and I am still having the same issues
First I open the file and save it to a variable to reuse later:
#Open for reading and save the file information to text
fin = open('test.txt','r')
text = fin.read()
fin.close
#Make modifications and write to new file
fout = open('test_new.txt','w')
for line in text:
whitespaceloc = line.find(' ')
newline = line[whitespaceloc:]
fout.write(newline)
fout.close()
I have also tried using the 'with' keyword with no luck,
When I open test_new.txt it is empty
What is going on here?
My advice on how to do this would be:
1) Read the file to a buffer:
with open('file.txt','r') as myfile:
lines=myfile.readlines()
2) Now close and overwrite the same file with any changes you want to do just as you did before:
with open('file.txt','w') as myfile:
for line in lines:
whitespaceloc = line.find(' ')
newline = line[whitespaceloc:]
myfile.write("%s" %newline)

How to seek and append to a binary file in python?

I am having problems appending data to a binary file. When i seek() to a location, then write() at that location and then read the whole file, i find that the data was not written at the location that i wanted. Instead, i find it right after every other data/text.
My code
file = open('myfile.dat', 'wb')
file.write('This is a sample')
file.close()
file = open('myfile.dat', 'ab')
file.seek(5)
file.write(' text')
file.close()
file = open('myfile.dat', 'rb')
print file.read() # -> This is a sample text
You can see that the seek does not work. How do i resolve this? are there other ways of achieving this?
Thanks
On some systems, 'ab' forces all writes to happen at the end of the file. You probably want 'r+b'.
r+b should work as you wish
Leave out the seek command. You already opened the file for append with 'a'.
NOTE : Remember new bytes over write previous bytes
As per python 3 syntax
with open('myfile.dat', 'wb') as file:
b = bytearray(b'This is a sample')
file.write(b)
with open('myfile.dat', 'rb+') as file:
file.seek(5)
b1 = bytearray(b' text')
#remember new bytes over write previous bytes
file.write(b1)
with open('myfile.dat', 'rb') as file:
print(file.read())
OUTPUT
b'This textample'
remember new bytes over write previous bytes

Categories