when i run this code in Python 3.4.2(win7-64) it doesn't work! it creates file but nothing in it.(0 bytes)
I don't know what is the problem? Help- Thanks
Windo
import pickle
f=open ("G:\\database.txt","wb")
pickle.dump (12345,f)
You have to close the file object that you have opened. So just add the line
f.close()
at the end and it will work.
As an alternative, you can also use the with statement to open the file, then it will automatically close the file for you when it's done:
import pickle
with open("G:\\database.txt", "wb") as f:
pickle.dump( 12345, f )
Related
I have been struggling with this problem for a while but can't seem to find a solution for it. The situation is that I need to open a file in browser and after the user closes the file the file is removed from their machine. All I have is the binary data for that file. If it matters, the binary data comes from Google Storage using the download_as_string method.
After doing some research I found that the tempfile module would suit my needs, but I can't get the tempfile to open in browser because the file only exists in memory and not on the disk. Any suggestions on how to solve this?
This is my code so far:
import tempfile
import webbrowser
# grabbing binary data earlier on
temp = tempfile.NamedTemporaryFile()
temp.name = "example.pdf"
temp.write(binary_data_obj)
temp.close()
webbrowser.open('file://' + os.path.realpath(temp.name))
When this is run, my computer gives me an error that says that the file cannot be opened since it is empty. I am on a Mac and am using Chrome if that is relevant.
You could try using a temporary directory instead:
import os
import tempfile
import webbrowser
# I used an existing pdf I had laying around as sample data
with open('c.pdf', 'rb') as fh:
data = fh.read()
# Gives a temporary directory you have write permissions to.
# The directory and files within will be deleted when the with context exits.
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, 'example.pdf')
# write a normal file within the temp directory
with open(temp_file_path, 'wb+') as fh:
fh.write(data)
webbrowser.open('file://' + temp_file_path)
This worked for me on Mac OS.
I tried this code posted 2 years ago:
import subprocess
with open("output.txt", "wb") as f:
subprocess.check_call(["python", "file.py"], stdout=f)
import sys
import os.path
orig = sys.stdout
with open(os.path.join("dir", "output.txt"), "wb") as f:
sys.stdout = f
try:
execfile("file.py", {})
finally:
sys.stdout = orig
It hangs up the terminal until I ctl-z and then it crashes the terminal but prints the output.
I'm new to coding and am not sure how to resolve. I'm obviously doing something wrong. Thanks for your help.
You can simply open and write to the file with write.
with open('output.txt', 'w') as f:
f.write('output text') # You can use a variable from other data you collect instead if you would like
Since you are new to coding, i'll just let you know that opening a file using with will actually close it automatically after the indented code is ran. Good luck with your project!
I have one file named Account.txt in SFTP server, and I'm trying to appending a line to this file. This is my effort:
from io import StringIO
from pysftp import Connection, CnOpts
cnopts = CnOpts()
cnopts.hostkeys = None
with Connection('ftpserver.com'
,username= 'username'
,password = 'password'
,cnopts=cnopts
) as sftp:
with sftp.cd('MY_FOLDER'):
f = sftp.open('Account.txt', 'ab')
data='google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google'
f.write(data+'\n')
When I run this above code, the file was overwritten, instead of appended. So, How can append new line but still keep the old lines in the file?
For example:
Account.txt file:
facebook|11111|Jack|Will||true|2018-09-21|2018-09-21|facebook
facebook|22222|Jack|Will||true|2018-09-21|2018-09-21|facebook
And now I want to add line "google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google" to the file.
The result I'm expecting:
Account.txt file
facebook|11111|Jack|Will||true|2018-09-21|2018-09-21|facebook
facebook|22222|Jack|Will||true|2018-09-21|2018-09-21|facebook
google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google
Hope you guys can understand. Leave a comment if you don't. Thank you.
Your code works for me with OpenSSH SFTP server.
Maybe it's a bug in Core FTP server.
You can instead try manually seeking file write pointer to the end of the file:
with sftp.open('Account.txt', 'r+b') as f:
f.seek(0, os.SEEK_END)
data='google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google'
f.write(data+'\n')
An addition to Martin's answer:
When using r+b, it will fail if the file does not exist yet. Use a+ instead if you want the file to be created if it does not exist, in a similar way to Difference between modes a, a+, w, w+, and r+ in built-in open function?.
Then no f.seek(0, os.SEEK_END) will be needed:
with sftp.open('test.txt', 'a+') as f:
f.write('hello')
In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:
An error occurred while reading file. [WinError 32] The process cannot access the file because it is being used by another process
I'm reading file using with, and I've tried f.close() and also f.closed but its the same error every time.
This is my code:
f = open(filePath)
with f:
line = f.readline().strip()
tempLst = line.split(fileSeparator)
if(len(lstHeader) != len(tempLst)):
headerErrorMsg = "invalid headers"
hjsonObj["Line No."] = 1
hjsonObj["Error Detail"] = headerErrorMsg
data['lstErrorData'].append(hjsonObj)
data["status"] = True
f.closed
return data
f.closed
after this code I call the remove function:
os.remove(filePath)
Edit: using with open(filePath) as f: and then trying to remove the file gives the same error.
Instead of:
f.closed
You need to say:
f.close()
closed is just a boolean property on the file object to indicate if the file is actually closed.
close() is method on the file object that actually closes the file.
Side note: attempting a file delete after closing a file handle is not 100% reliable. The file might still be getting scanned by the virus scanner or indexer. Or some other system hook is holding on to the file reference, etc... If the delete fails, wait a second and try again.
Use below code:
import os
os.startfile('your_file.py')
To delete after completion:
os.remove('your_file.py')
This
import os
path = 'path/to/file'
with open(path) as f:
for l in f:
print l,
os.remove(path)
should work, with statement will automatically close the file after the nested block of code
if it fails, File could be in use by some external factor. you can use Redo pattern.
while True:
try:
os.remove(path)
break
except:
time.sleep(1)
There is probably an application that is opening the file; check and close the application before executing your code:
os.remove(file_path)
Delete files that are not used by another application.
Using app.open_resource('foobar.txt', 'w') generates the error Resources can only be opened for reading in flask.
Is there a way to open a resource to write to it?
If not, can you get the path of the resource using flask and then I can open it manually and write to it.
This should work:
import os
f = open(os.path.join(app.root_path, 'foobar.txt'), 'w')
This is more convenient:
import os
with open(os.path.join(app.root_path, 'foobar.txt'), 'w') as f:
...