Why does the following interaction fail? (python 3.6.1)
>>> with open('an_image.png', 'rb') as f, open('~/Desktop/an_image.png', 'wb') as g:
... g.write(f.read())
...
Traceback (most recent call last): File "<stdin>", line 1, in
<module> FileNotFoundError: [Errno 2] No such file or directory:
'~/Desktop/an_image.png'
>>>
Isn't the 'w' mode supposed to create the file if it doesn't exist?
As Dilettant said, remove the ~. You can specify the absolute path manually, or use os.path.expanduser:
import os
desktop_img = os.path.expanduser('~/Desktop/an_image.png')
# desktop_img will now be /home/username/Desktop/an_image.png
with open('an_image.png', 'rb') as f, open(desktop_img, 'wb') as g:
g.write(f.read())
Related
I saved csv file in (C:/Users/kgu/PycharmProjects/untitled1/test1.py). named as testdata.csv
my code is :
import csv
f=open('testdata.csv','r',encoding='utf-8')
And the error message is here :
C:\Users\kgu\Anaconda3\python.exe
C:/Users/kgu/PycharmProjects/untitled1/test1.py
Traceback (most recent call last):
File "C:/Users/kgu/PycharmProjects/untitled1/test1.py", line 3, in <module>
f=open('testdata.csv','r',encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: 'testdata.csv'
Process finished with exit code 1
I did save the testdata.csv in the python project folder.
I don't know what is wrong in it.
If you use Pandas, you can try:
import pandas as pd
filepath = "/yourfilepath/yourfile.csv"
# check your sep (";" , "," ...)
f = pd.read_csv(filepath, encoding="utf-8", sep="yoursep")
You could do it like this - if you are in the right working directory:
with open(testdata.csv', 'rb') as csvfile:
data = [x for x in csv.reader(csvfile, delimiter='yourdelimiter')]
I'm trying to Batch Edit all JSON files within a folder, and saving each of them as new JSON all at once, instead of doing each one.
def new_json(filename):
with open(filename, 'r+') as f:
json_data = json.load(f)
somefunction()
f.seek(0)
base, ext = os.path.splitext(filename)
out_file = open(base + '_expand' + ext, 'w')
json.dump(room_data, out_file, indent=4)
def batchRun(foldername):
for f in os.listdir(foldername):
new_json(f)
folder = 'testing'
batchRun(folder)
When I try to run the batchRun function, it gives me an error
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
batchRun(folder)
File "<pyshell#8>", line 3, in batchRun
new_json(f)
File "<pyshell#6>", line 2, in new_json
with open(filename, 'r+') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'simple_json.txt'
And I know for sure simple_json.txt and other files are within that folder that I defined, so I'm not sure what's happening.
os.listdir gives you a list of file names, not file paths. You can use os.path.join to get the full file path:
def batchRun(foldername):
for f in os.listdir(foldername):
new_json(os.path.join(foldername, f))
Why am I getting
Traceback (most recent call last): File "C:\temp\py\tesst.py", line 8, in <module>
os.remove( PATH ) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
'C:\temp\py\test.txt'
import os
PATH = r'C:\temp\py\test.txt'
f = open ( PATH,'w')
f.write('test\n')
f.close;
os.remove( PATH )
Am I missing something?
You are calling f.close instead of f.close(). It would be better to open the file contextually so it will be closed automatically.
import os
PATH = r'C:\temp\py\test.txt'
with open(PATH, 'wb') as f:
f.write('test\n')
os.remove(PATH)
Whenever I try to overwrite a file in Python 2.7 this is what happens, code:
a = open('hello.txt')
a.write('my name is mark')
And my error is:
Traceback (most recent call last):
File "C:\Users\Mark Malkin\Desktop\New folder\opener.py", line 2, in <module>
a.write('my name is mark')
IOError: File not open for writing
From docs on open:
If mode is omitted, it defaults to 'r'.
To write instead use,
a = open('hello.txt', 'w')
Or better yet,
with open('hello.txt', 'w') as f:
f.write('my name is mark')
So, I'm trying to unzip a .jar file using this code:
It won't unzip, only 20 / 500 files, and no folders/pictures
The same thing happens when I enter a .zip file in filename.
Any one any suggestions?
import zipfile
zfilename = "PhotoVieuwer.jar"
if zipfile.is_zipfile(zfilename):
print "%s is a valid zip file" % zfilename
else:
print "%s is not a valid zip file" % zfilename
print '-'*40
zfile = zipfile.ZipFile( zfilename, "r" )
zfile.printdir()
print '-'*40
for info in zfile.infolist():
fname = info.filename
data = zfile.read(fname)
if fname.endswith(".txt"):
print "These are the contents of %s:" % fname
print data
filename = fname
fout = open(filename, "w")
fout.write(data)
fout.close()
print "New file created --> %s" % filename
print '-'*40
But, it doesn't work, it unzips maybe 10 out of 500 files
Can anyone help me on fixing this?
Already Thanks!
I tried adding, what Python told me, I got this:
Oops! Your edit couldn't be submitted because:
body is limited to 30000 characters; you entered 153562
and only the error is :
Traceback (most recent call last):
File "C:\Python27\uc\TeStINGGFDSqAEZ.py", line 26, in <module>
fout = open(filename, "w")
IOError: [Errno 2] No such file or directory: 'net/minecraft/client/ClientBrandRetriever.class'
The files that get unzipped:
amw.Class
amx.Class
amz.Class
ana.Class
ane.Class
anf.Class
ang.Class
ank.Class
anm.Class
ann.Class
ano.Class
anq.Class
anr.Class
anx.Class
any.Class
anz.Class
aob.Class
aoc.Class
aod.Class
aoe.Class
This traceback tells you what you need to know:
Traceback (most recent call last):
File "C:\Python27\uc\TeStINGGFDSqAEZ.py", line 26, in <module>
fout = open(filename, "w")
IOError: [Errno 2] No such file or directory: 'net/minecraft/client/ClientBrandRetriever.class'
The error message says that either the file ClientBrandRetriever.class doesn't exist or the directory net/minecraft/client does not exist. When a file is opened for writing Python creates it, so it can't be a problem that the file does not exist. It must be the case that the directory does not exist.
Consider that this works
>>> open('temp.txt', 'w')
<open file 'temp.txt', mode 'w' at 0x015FF0D0>
but this doesn't, giving nearly identical traceback to the one you are getting:
>>> open('bogus/temp.txt', 'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'bogus/temp.txt'
Creating the directory fixes it:
>>> os.makedirs('bogus')
>>> open('bogus/temp.txt', 'w')
<open file 'bogus/temp.txt', mode 'w' at 0x01625D30>
Just prior to opening the file you should check if the directory exists and create it if necessary.
So to solve your problem, replace this
fout = open(filename, 'w')
with this
head, tail = os.path.split(filename) # isolate directory name
if not os.path.exists(head): # see if it exists
os.makedirs(head) # if not, create it
fout = open(filename, 'w')
If python -mzipfile -e PhotoVieuwer.jar dest works then you could:
import zipfile
with zipfile.ZipFile("PhotoVieuwer.jar") as z:
z.extractall()