I am new to Python and I have programmed a very basic program which opens a pre-made file reads it, then closes it, through normal Python syntax:
f = open("file", "r+")
f.read()
f.close()
However, once run, this program produces no output.
Is there a problem with my syntax, or is there an error in my PyCharm installation?
This is supposed to happen. f.read() does not print things to the screen. It returns them, just like open() returns f. If you want to print things, you need to call the print() function (under Python 3) or use the print statement (under Python 2).
Related
I have a problem with the read() function in Python, it just doesn't read the file:
with open("D:\\Joseph\\pythontest.txt", "w+") as f:
f.write("Hello World")
print(f.read())
It doesn't show anything in the output (not even an error), just finishes the program.
screenshot of code in Sublime IDE showing nothing printed
You are writing to the file, but you didn't go back in the file. The "cursor" is located after what you wrote.
Try f.seek(0) to go at the beginning of your file after writing to it.
Your code is trying to write it as you have ”w+” as a second param of open() call. Please use the open without the second parameter.
I am using Windows 7, Python 2.7. I am trying to write to a text file with one file ID in one program that continues writing new data/numbers for several minutes.
In a separate program, after the writing has begun, I am trying to read from the file that is being written in order to update and plot the data in the file.
While the first program is writing the data, I am unable to read the data until it finishes. Here is some example code to illustrate my point:
Program 1:
import time
fid = open("test1.txt", "w+")
for i in range(0, 5):
fid.write(str(i) + "\n")
print(i)
time.sleep(5)
fid.close()
Program 2:
fid = open("test1.txt", "r+")
dataList = fid.read().splitlines()
print(dataList)
fid.close()
Executing Program 2 while Program 1 is running does not allow me to see any changes until Program 1 is completed.
Is there a way to fix this issue? I need to keep the reading and writing in two separate programs.
This might be caused by buffering in program 1. You can try flushing the output in program 1 after each write:
fid.write(str(i) + "\n")
fid.flush()
Another thing you can try is to run the Python interpreter in unbuffered mode for program 1. Use the python -u option.
Also, do you need to open the file for update (mode r+) in program 2? If you just want to read it, mode r is sufficient, or you can omit the mode when calling open().
I've added the following line to a python file in order to output all print strings to a file:
sys.stdout = open(logf, 'wb')
This does what I wanted, but also stops all print strings from appearing in the terminal. Is there a way to configure stdout to print to both destinations? (I'm trying to avoid writing a function for each use of print because there are many and it's a lot to rewrite. Also, I've perused several similar topics, but I haven't found a simple method.)
def fprint(output):
print output
with open("somefile.txt", "a") as f:
f.write("{}\n".format(output))
This function would do it for you, use instead of print.
I'm really frustrated with this strange behaviour of Python all of a sudden. I've been writing to files all sorts of data but since today morning it just doesn't seem to work. I've referred to all these before posting:
How to redirect 'print' output to a file using python?
Failed to write to file but generates no Error
Unable to write data into a file using python
Unable to write list of elements to a file using python
Have tried all following commands but it just doesn't write anything to the delete.txt file. What's happening?
fl=open('delete.txt','w')
fl.write(msg) <--Doesnt work,tried this also
fl.write('%s' %msg) <--Doesnt work,tried this also
fl.write("at least write this") <-- Doesnt work,tried this also
print (msg) <- WORKS
Code:
for i in hd_com.comment_message[1:500]:
fl=open('delete.txt','wb')
try:
if len(i)>40:
mes=processComUni(i)
proc=nltk.tokenize.word_tokenize(mes)
#print proc
pos=nltk.pos_tag(proc)
for i in pos:
if ((i[1]=="NN") or (i[1]=="NNP") or (i[1]=="NNS")) and len(i[0])>2:
#print i[0],i[1]
for j in home_depo_inv:
if i[0] in j.split() and (i[0]!='depot' and i[0]!='home' and i[0]!='store' and i[0]!='por' and i[0]!='get' and i[0]!='house' and i[0]!='find' and i[0]!='part' and i[0]!='son' and i[0]!='put' and i[0]!='lot' and i[0]!='christmas' and i[0]!='post'):
a=re.findall(i[0],j)
fl.write(str(i))<--Doesnt work,tried this also
fl.write(str(mes))<--Doesnt work,tried this also
fl.write("\n")<--Doesnt work,tried this also
fl.write("hello")<--Doesnt work,tried this also
fl.flush()
break
except:
continue
fl.close()
More code:
type(mes) = str
mes="omg would love front yard"
Your snippet's indentation is totally messed up, but anyway: your code starts with:
for i in hd_com.comment_message[1:500]:
fl=open('delete.txt','wb')
which means you reopen the file for writing on each iteration, erasing whatever might have been written by the previous iteration.
You need to flush the output stream explicitly when writing to a file handle like that.
f = open("test.txt", "w")
f.write("this is a test\n")
# no text in the output file at this point
f.flush()
# buffers are flushed to the file
f.write("this, too, is a test\n")
# again, line doesn't show in the file
f.close()
# closing the file flushes the buffers, text appears in file
From the documentation of file.write:
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
I'm trying to read the contents of a file in a single method call.
I don't want to have to worry about opening the file, reading from the file, and then closing the file (3 method calls).
I just want the content.
In ruby, there is File.read("/path/to/file"), which returns the contents of that file and properly closes it. Is there an equivalent in Python?
You can concatenate two instructions to get the same behaviour :/. But then the file isn't properly closed.
file = open("/path/to/file","r").read()
edit:
Best option as far as I know leaves you needing 2/3 you mention. Just use the with statement so you don't have to worry about closing said file.
with open("/path/to/file","r") as file:
text = file.read()
You can use a Context Manager in Python, which is available from Python 2.5.
with open('yourfile') as f:
contents = f.read()
It will automatically, open and close the file for you. The default mode is 'r' which stands for reading.
There is no such function included with Python. It's simple enough to define one, though.
def read_whole_file(path):
with open(path) as f:
return f.read()