it does work if I type this on python shell
>>> f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
>>> f.read()
'plpw eeeeplpw eeeeplpw eeee'
>>> f.close()
but if I create a python program, i doesn't work.
import os
f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
f.read()
f.close()
i saved this piece of code by using text editor.
if I execute this program in python shell, it shows nothing.
please tell me why..
In the interactive prompt, it automatically prints anything a function call returns. That means the return value of f.read() is printed automatically. This won't happen when you put it in a program however, so you will have to print it yourself to have it show up.
import os
f = open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
print f.read() # use print(f.read()) in Python 3
f.close()
Another suggestion I would make would be to use a with block:
import os
with open(os.path.join(os.getcwd(), 'test1.txt'), 'r') as f:
print f.read()
This means that you won't have to worry about manually closing the file afterwards.
Related
I have the following code:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
where I'd like to replace the old content that's in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?
You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:
import re
myfile = "path/test.xml"
with open(myfile, "r+") as f:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
f.truncate()
The other way is to read the file then open it again with open(myfile, 'w'):
with open(myfile, "r") as f:
data = f.read()
with open(myfile, "w") as f:
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).
By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
Using truncate(), the solution could be
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
in my case the following code did the trick
with open("output.json", "w+") as outfile: #using w+ mode to create file if it not exists. and overwrite the existing content
json.dump(result_plot, outfile)
Using python3 pathlib library:
import re
from pathlib import Path
import shutil
shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
Similar method using different approach to backups:
from pathlib import Path
filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
In that part of code I make the files txt and its working
import sys
for i in range(6):
file = open('teste{:d}.txt'.format(i), 'a')
sys.stdout = file
And now the problem, the files were created but in this part of code it didnt work, i can compile but the files are empty
for i in range(1,6):
f=open('100K_Array_{:d}.txt'.format(i), 'r')
alist = f.readlines()
quickSort(alist)
print(alist)
f.close()
It appears to me that you haven't closed your output file properly. You should either use
with open('teste{:d}.txt', 'a') as file:
...
in which case with statement will handle closing the file for you. Otherwise you need to add file.close() to your current code.
When I look at what it wrote it's always double. For example if I write 'dog' ill get 'dogdog'. Why?
Reading and writing to file, filename taken from command line arguments:
from sys import argv
script,text=argv
def reading(f):
print f.read()
def writing(f):
print f.write(line)
filename=open(text)
#opening file
reading(filename)
filename.close()
filename=open(text,'w')
line=raw_input()
filename.write(line)
writing(filename)
filename.close()
As I said the output I am getting is the double value of what input I am giving.
You are getting double value because you are writing two times
1) From the Function call
def writing(f):
print f.write(line)
2) By writing in file using filename.write(line)
Use this code:
from sys import argv
script,text=argv
def reading(f):
print f.read()
def writing(f):
print f.write(line)
filename=open(text,'w')
line=raw_input()
writing(filename)
filename.close()
And also no need to close file two times, once you finished all the read and write operations then just close it.
If you want to display each line and then write a new line, you should probably just read the entire file first, and then loop over the lines when writing new content.
Here's how you can do it. When you use with open(), you don't have to close() the file, since that's done automatically.
from sys import argv
filename = argv[1]
# first read the file content
with open(filename, 'r') as fp:
lines = fp.readlines()
# `lines` is now a list of strings.
# then open the file for writing.
# This will empty the file so we can write from the start.
with open(filename, 'w') as fp:
# by using enumerate, we can get the line numbers as well.
for index, line in enumerate(lines, 1):
print 'line %d of %d:\n%s' % (index, len(lines), line.rstrip())
new_line = raw_input()
fp.write(new_line + '\n')
Normally when I write stdout to a file, I do it like this.
import sys
sys.stdout = open(myfile, 'w')
print "This is in a file."
Now, this method looks ugly to me, and I've heard here and there that there is a better method. If so, what is this better method?
You can also make use of the fact that print can actually wrote to a file.
with open("file.txt", "w") as f:
print("Hello World!", file=fd)
NB: This is Python 3.x Syntax only as print is a function in Python 3.x.
For Python 2.x you can however do:
from __future__ import print_function
Otherwise the same can be achieved with:
with open("file.txt", "w") as fd:
print >> fd, "Hello World!"
See: print() from Python 3.x Docs.
Print directly to the file, using either
with open(myfile, 'w') as fh:
fh.write("This is in a file.\n")
or
with open(myfile, 'w') as fh:
print >>fh, "This is in a file."
or
from __future__ import print_function
with open(myfile, 'w') as fh:
print("This is in a file.", file=fh)
You can do it as shown in the other answers, but it gets kind of old specifying the output file in every statement. So I understand the urge to just redirect sys.stdout. But yes, the way you propose doing it is not as elegant as it could be. Adding proper error handling will make it even uglier. Fortunately, you can create a handy context manager to address these issues:
import sys, contextlib
#contextlib.contextmanager
def writing(filename, mode="w"):
with open(filename, mode) as outfile:
prev_stdout, sys.stdout = sys.stdout, outfile
yield prev_stdout
sys.stdout = prev_stdout
Usage:
with writing("filename.txt"):
print "This is going to the file"
print "In fact everything inside the with block is going to the file"
print "This is going to the console."
Note that you can use the as keyword to get the previous stdout, so you can still print to the screen inside the with block:
with writing("filename.txt") as stdout:
print "This is going to the file"
print >> stdout, "This is going to the screen"
print "This is going to the file again"
All the tutorials I can find follow the same format which isn't working.I don't get an error message but I don't get normal output. What I get appears to be the file description at some memory location.
# file_test
ftpr= open("file","w")
ftpr.write("This is a sample line/n")
a=open("file","r")
print a
#This is the result
<open file 'file', mode 'r' at 0x00000000029DDDB0>
>>>
Do you want to read the contents of the file? Try print a.readlines().
Ie:
with open('file', 'w') as f:
f.write("Hello, world!\nGoodbye, world!\n")
with open('file', 'r') as f:
print f.readlines() # ["Hello, world!\n", "Goodbye, world!\n"]
FYI, the with blocks, if you're unfamiliar with them, ensure that the open()-d files are close()-d.
This is not the correct way to read the file. You are printing return value from open call which is object of file type. Do like this for reading and writing.
for writing
f=open("myfile","w")
f.write("hello\n")
f.write("This is a sample line/n")
f.close()
For reading
f=open("file","r")
string = f.read()
print("string")
f.close()