The following is Snippet of my program:
with open(completepathname,'wb') as f:
print ('file opened')
print(f)
while True:
print('receiving data...')
print('hello')
data = send_receive_protocol.recv_msg(conn)
#print('hi')
print(data)
if not data:
print('printing1')
break
print('printing')
data1=data.encode()
print(data1)
f.write(data1)#write to file
f.close()
output prints correctly to the console, but if I go open up the file it's blank. If I delete the file and execute my program again, the file is created but still is empty
The following snippet works as expected:
with open('test.txt', 'wb') as f:
while True:
data = 'test-data'
if not data:
break
data1 = data.encode('hex')
f.write(data1)
f.flush()
You should be careful not to .close() a file-like object and then continue to attempt to write to it. If you need to ensure the output is written right away, use .flush().
Related
I'm trying to send a file over a socket. Everything seems to be working properly except for the file not writing properly. I snipped the code down to the major issue but can send the full server and client code if necessary.
if inst == "send":
try:
print ("Receiving...")
l = s.recv(1024)
with open('torecv.py', 'wb') as f:
print ("Writing...")
newFile = l.decode("UTF-8")
f.write(newFile)
f.close()
print ("Done Receiving")
except:
pass
The output returns:
Receiving...
Writing...
and newFile saves the correct data which says to me that it is running f.write is the problem because "torecv.py" is empty.
I'm pretty new to python so go easy on me. Thanks!
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
f.close()
exec(s)
with open(masterpath, 'w') as g:
g.truncate()
g.close()
os.remove(masterpath)
Here I want to read something in a .txt file and then erase content and delete it. But it always shows it cannot delete it as 'The process cannot access the file because it is being used by another process'.
Actually what I need is to delete the .txt file, but it cannot delete immediately sometimes, so I erase the content at first in case that it will be read again. So is there any good way to read something in a .txt file and then delete this file as soon and stable as possible?
You should NOT call f.close() nor g.close(). It is called automatically by with statement.
remove the unnecessary close() statements to start - like #grapes mentioned - why are you truncating what you are deleting? just delete it...
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
exec(s)
except Error as e:
print(e)
else:
os.remove(masterpath)
FYI, it is bad form to execute the contents of a file if you do not control the contents of said file.
another option:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
try:
s = f.read()
except Error as e:
print(e)
else:
exec(s)
os.remove(masterpath)
Try to use short sleep in exception part:
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
f.close()
exec(s)
with open(masterpath, 'w') as g:
g.truncate()
g.close()
os.remove(masterpath)
except WindowsError:
time.sleep(sleep)
else:
break
Another way is to use:
os.remove(masterpath)
I am downloading dynamic data from api server and writing it to file by means of an endless loop in python. For whatever reason the program stops writing to file after couple thousand lines, while the program seems to be running. I am not sure where the problem is. The program does not give error, ie. it is not that the API server is refusing response. When restarted it continues as planned. I am using python 3.6 and win10.
Simplified version of the code looks something like:
import requests, json, time
while True:
try:
r = requests.get('https://someapiserver.com/data/')
line = r.json()
with open('file.txt', 'a') as f:
f.write(line)
time.sleep(5)
except:
print('error')
time.sleep(10)
Try opening the file first and keeping the lock on it like so:
import requests, json, time
f = open('file.txt', 'a')
while True:
try:
r = requests.get('https://someapiserver.com/data/')
line = r.json()
f.write(line)
f.flush()
time.sleep(5)
except:
print('error')
time.sleep(10)
f.close() # remember to close the file
The solution is ugly but it will do.
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
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.