Script doesn't read file - python

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.

Related

Nesting 'r' after opening a file in write mode

so I had an exercise asking to write to a file (using newlines) and then open it in reading mode. I did exactly that and the console outputs the right result. What happened was that I tried to do it within the 'w' mode code block and the console outputs nothing.
For example:
with open('test.txt', 'w') as wf:
nicknames = ["Big Tuna", "Prison Mike", "Booster Seat"]
wf.write('\n'.join(nicknames))
with open('test.txt', 'r') as rf:
print(rf.read())
I understand that the program only closes the file after the with statement, but I need clarification on my understanding of what's happening here.
So, what I understood so far is that the program first creates the test.txt file (test.txt did not exist in my file path) and then proceeds to convert and write the given contents into the test.txt file. After that, the nested with tries to open a file named test.txt in reading mode, but the console will not output anything because the program is trying to open a file that is already opened, that's why it cannot read into an already opened file.
Please correct me if I'm misunderstood the above because I am unsure whether or not I've understood it correctly, thank you.
That’s not what’s happening. Unix systems, at least, will happily let you open a file multiple times.
However, Python’s IO is buffered by default. You need to flush the data you’ve written out to the file before you can read the data from it. See https://docs.python.org/3/library/io.html#io.IOBase.flush for more information about this. (Summary: put wf.flush() after the wf.write(…) call and before attempting to read from it.

Python file not appending on Raspberry Pi

I'm quite new to Python and Pi'ing, and would like some help with appending a text file on a Raspberry Pi. My script will call a GET or a POST REST API and write the time, status and reason for each call.
I got the call information from grepit's comment in Simple URL GET/POST function in Python and it works great.
For appending my file, I use the following code:
#...Some working code...
dateNow = datetime.datetime.now()
string = ("\n" + dateNow.strftime("%c") + " - " + str(response.status) +
": " + response.reason + "\n")
with open('MyCallLog.txt', 'a+') as file:
file.write(string)
What I have read regarding similar issues, is that the file is not closed or flushed. However, if I try to debug using print(file.read()) outside the 'with' I get an error that is file is already closed and debugging inside the with displays nothing. I also tried it without the with and specifically stating file.close(). I have debugged the string variable using print(string) and it displays as intended.
Any suggestions?
Final notes:
I am aware that opening a file as 'a+' does open it in read and write mode. This is currently only for my debugging purposes.
When a file is opened in append mode using "a+" the cursor is positioned at the end of the file. That is why a call to .write() will append to the end of the file instead of overwriting it.
When you call file.read() in the with block, it is reading the file from the last character onwards, which is why your print output is empty.
To print the content you need to seek to the beginning of the file.
with open("myfile.txt", "a+") as file:
file.write("some_text")
file.seek(0)
print(file.read()) # "some_text"
Better yet, just open the file again for your debugging.
with open("myfile.txt", "a+") as file:
file.write("some_text")
with open("myfile.txt", "r") as file:
print(file.read())
Your code to append was actually correct. There should be a file in the CWD with all of your attempts in it.
Also, the reason that you get an error when you try to call .read() outside of the with block is because file.close() is implicitly called when the block exits.
open() returns a context manager. You can read about context managers in python here. They are very useful and great to know about. I write new context managers often at my job.

PyCharm outputs no text while reading file

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).

writing output for python not functioning

I am attempting to output a new txt file but it come up blank. I am doing this
my_file = open("something.txt","w")
#and then
my_file.write("hello")
Right after this line it just says 5 and then no text comes up in the file
What am I doing wrong?
You must close the file before the write is flushed. If I open an interpreter and then enter:
my_file = open('something.txt', 'w')
my_file.write('hello')
and then open the file in a text program, there is no text.
If I then issue:
my_file.close()
Voila! Text!
If you just want to flush once and keep writing, you can do that too:
my_file.flush()
my_file.write('\nhello again') # file still says 'hello'
my_file.flush() # now it says 'hello again' on the next line
By the way, if you happen to read the beautiful, wonderful documentation for file.write, which is only 2 lines long, you would have your answer (emphasis mine):
Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.
If you don't want to care about closing file, use with:
with open("something.txt","w") as f:
f.write('hello')
Then python will take care of closing the file for you automatically.
As Two-Bit Alchemist pointed out, the file has to be closed. The python file writer uses a buffer (BufferedIOBase I think), meaning it collects a certain number of bytes before writing them to disk in bulk. This is done to save overhead when a lot of write operations are performed on a single file.
Also: When working with files, try using a with-environment to make sure your file is closed after you are done writing/reading:
with open("somefile.txt", "w") as myfile:
myfile.write("42")
# when you reach this point, i.e. leave the with-environment,
# the file is closed automatically.
The python file writer uses a buffer (BufferedIOBase I think), meaning
it collects a certain number of bytes before writing them to disk in
bulk. This is done to save overhead when a lot of write operations are
performed on a single file. Ref #m00am
Your code is also okk. Just add a statement for close file, then work correctly.
my_file = open("fin.txt","w")
#and then
my_file.write("hello")
my_file.close()

Subprocess file output needs to close before reading

I'm trying to use a subprocess to write the output to a data file, and then parse through it in order to check for some data in it. However, when I need to do the reading through the file's lines, I always get a blank file unless I close the file and then reopen it. While it works, I just don't like having to do this and I want to know why it happens. Is it an issue with subprocess, or another intricacy of the file mode?
dumpFile=open(filename,"w+")
dump = subprocess.Popen(dumpPars,stdout=dumpFile)
dump.wait()
At this point, if I try to read the file, I get nothing. However, it works fine by doing these commands after:
dumpFile.close()
dumpFile=open(filename,"r")
The with statement automatically closes the file after the block ends:
with open(filename, "w+") as dumpFile:
dump = subprocess.Popen(dumpPars, stdout=dumpFile)
dump.wait()
with open(filename, "r") as dumpFile:
# dumpFile reading code goes here
You probably need to seek back to the beginning of the file, otherwise the file pointer will be at the end of the file when you try to read it:
dumpFile.seek(0)
However, if you don't need to actually store dumpFile, it's probably better to do something like:
dump = = subprocess.Popen(dumpPars,stdout=subprocess.PIPE)
stdoutdata,_ = dump.communicate() #now parse stdoutdata
unless your command produces large volumes of data.
If you want to read what you've already written, either close and reopen the file, or "rewind" it - seek to offset 0.
If you want to read the file while it is being written, you can do so (don't even need to write it to disk), see this other question Capture output from a program

Categories

Resources