Consider the following code:
file = open("f.txt", 'w')
file.write("abc")
file.close()
with open("f.txt", "r+") as f:
f.read(1)
f.write("d")
I'm expecting adc after running this, but it turns out to be abcd.
Why wouldn't the content be overwritten?
Related
The code is used to convert the data from hexadecimal to binary works perfect but, but when I redirect the output to the file, the output file is empty
here is the code
for file in glob.glob("g1.txt.out"):
print file
myfile = open(file, "r")
outfile= open( file + ".binary",'a+')
for line in myfile:
data_binary="{0:16b}".format(int(line, 16))
print >> outfile,data_binary # redirect code.
Instead of redirecting the output of print, you can write directly to the output file:
with open("g1.txt.out", "r") as my_file, open("g1.txt.out.binary",'a+') as out_file:
for line in my_file:
data_binary = "{0:16b}\n".format(int(line, 16))
out_file.write(data_binary)
You need to close you files, as io is buffered. Always remember to close all your open files to save data.
for file in glob.glob("g1.txt.out"):
print file
myfile = open(file, "r")
outfile= open( file + ".binary",'a+')
for line in myfile:
data_binary="{0:16b}".format(int(line, 16))
print >> outfile,data_binary # redirect code.
myfile.close()
outfile.close()
Or even better learn with statement, which will do it automatically.
with open(filename) as f:
data = f.read()
do something with data
Could someone give me some guidance on how you would get the contents of your text file on my python code without opening up the text file in another window?
Just point me in the right direction on how I should do it (No need for solutions)
with open(workfile, 'r') as f:
for line in f:
print line
If you don't use the context manager (the with statement) you will need to explicitly call f.close(), for example:
f = open('workfile', 'r')
line = f.readline()
print line
f.close()
file = open("your_file.txt", "r")
file.read()
I need some help Im trying to display the text files contents (foobar) with this code
text = open('C:\\Users\\Imran\\Desktop\\text.txt',"a")
rgb = text.write("foobar\n")
print (rgb)
text.close()
for some reason it keeps displaying a number. If anyone could help that would be awesome, thanks in advance
EDIT: I am Working with Python 3.3.
Print the contents of the file like this:
with open(filename) as f:
for line in f:
print(line)
Use with to ensure that the file handle will be closed when you are finished with it.
Append to the file like this:
with open(filename, 'a') as f:
f.write('some text')
# Open a file
fo = open("foo.txt", "r+")
str = fo.read();
print "Read String is : ", str
# Close opend file
fo.close()
More: http://www.tutorialspoint.com/python/python_files_io.htm
You are printing the number of written bytes. That won't work. Also you might need to open the file as RW.
Code:
text = open('...', "a")
text.write("foo\n")
text = open('...', "r")
print text.read()
If you want to display the contents of the file open it in read mode
f=open("PATH_TO_FILE", 'r')
And then print the contents of file using
for line in f:
print(line) # In Python3.
And yes, don't forget to close the file pointer f.close() after you finish the reading
I have to read in a file, change a sections of the text here and there, and then write out to the same file.
Currently I do:
f = open(file)
file_str = f.read() # read it in as a string, Not line by line
f.close()
#
# do_actions_on_file_str
#
f = open(file, 'w') # to clear the file
f.write(file_str)
f.close()
But I would imagine that there is a more pythonic approach that yields the same result.
Suggestions?
That looks straightforward, and clear already. Any suggestion depends on how big the files are. If not really huge that looks fine. If really large, you could process in chunks.
But you could use a context manager, to avoid the explicit closes.
with open(filename) as f:
file_str = f.read()
# do stuff with file_str
with open(filename, "w") as f:
f.write(file_str)
If you work line by line you can use fileinput with inplace mode
import fileinput
for line in fileinput.input(mifile, inplace=1):
print process(line)
if you need to process all the text at once, then your code can be optimized a bit using with that takes care of closing the file:
with open(myfile) as f:
file_str = f.read()
#
do_actions_on_file_str
#
with open(myfile, 'w') as f:
f.write(file_str)
I have an XML file that contains an illegal character, I am iterating through the file, removing the character from all of the lines and storing the lines in a list. I now want to write those same lines back into the file and overwrite what is already there.
I tried this:
file = open(filename, "r+")
#do stuff
Which is only appending the results to the end of the file, I would like to overwrite the existing file.
And this:
file = open(filename, "r")
#read from the file
file.close()
file = open(filename, "w")
#write to file
file.close()
This gives me a Bad File Descriptor error.
How can i read and write to the same file?
Thanks
You could re-write the lines list with writelines function.
with open(filename, "r") as f:
lines = f.readlines()
#edit lines here
with open(filename, "w") as f:
f.writelines(lines)
The reason you're appending to the end of the file the whole time is that you need to seek to the beginning of the file to write your lines out.
with open(filename, "r+") as file:
lines = file.readlines()
lines = [line.replace(bad_character, '') for line in lines]
file.seek(0)
file.writelines(lines)
file.truncate() # Will get rid of any excess characters left at the end of the file due to the length of your new file being shorter than the old one, as you've removed characters.
(Decided to just use the context manager syntax myself.)