Python file open/close every time vs keeping it open until the process is finished
Tag : python , By : Frank Rotolo
Date : March 29 2020, 07:55 AM
wish of those help You should definitely try to open/close the file as little as possible Because even comparing with file read/write, file open/close is far more expensive f=open('test1.txt', 'w')
for i in range(1000):
f.write('\n')
f.close()
for i in range(1000):
f=open('test2.txt', 'a')
f.write('\n')
f.close()
|
Why I can't read anything with File.open in python when I open the file to write first?
Date : March 29 2020, 07:55 AM
help you fix your problem , You never closed the file with this line of code: f.close
with open('day_temps.txt', 'w') as handle:
handle.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")
with open('day_temps.txt', 'w') as handle:
handle.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")
def get_stats(file_name):
with open(file_name, 'r') as handle:
numbers = map(float, handle.read().split(','))
return min(numbers), max(numbers), sum(numbers) / len(numbers)
if __name__ == '__main__':
stats = get_stats('day_temps.txt')
print "({0:.5}, {1:.5}, {2:.5})".format(*stats)
|
Python: when writing to a large file, keep the file open or to open it and append to it as needed?
Date : March 29 2020, 07:55 AM
To fix the issue you can do Opening and closing the files definitely has a cost. However if your legacy program takes one or more second to respond you propably won't notice. def func1():
for x in range(1000):
x = str(x)
with open("test1.txt", "a") as k:
k.write(x)
1 loops, best of 3: 2.47 s per loop
def func2():
with open("test2.txt", "a") as k:
for x in range(1000):
x = str(x)
k.write(x)
100 loops, best of 3: 6.66 ms per loop
def func3(file):
for x in range(10):
x = str(x)
with open(file, "a") as k:
k.write(x)
10 loops, best of 3: 33.4 ms per loop
1 loops, best of 3: 24.5 s per loop
|
Python PIL - open image from file object: File not open for reading
Date : November 14 2020, 04:51 PM
hop of those help? You opened the file for writing, not reading. You'd have to use a dual mode, and first rewind the file pointer: with open('myimage.png', 'w+b') as imgfile:
imgfile.write(decodestring(base64_image))
imgfile.seek(0)
f = Image.open(imgfile)
from io import BytesIO
imgfile = BytesIO(decodestring(base64_image))
f = Image.open(imgfile)
|
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You can access command line arguments passed to your script using sys.argv. As long as you want to pass these arguments to some third-party application(which is an executable binary) you should use the subprocess module as os.startfile is meant to start a file with its associated application. import sys
import subprocess
def main():
if len(sys.argv) == 1:
path = sys.argv[0]
subprocess.run(['/path/to/my.exe', path])
else:
print('Usage myscript.py <path>')
if __name__ == "__main__":
main()
|