Can't overwrite file on Windows - python

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

Related

Python fails writing to a file citing 'FileNotFoundError'

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

TypeError - What does this error mean?

So, i've been writing this program that takes a HTMl file, replaces some text and puts the return back into a different file in a different directory.
This error happened.
Traceback (most recent call last):
File "/Users/Glenn/jack/HTML_Task/src/HTML Rewriter.py", line 19, in <module>
with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/posixpath.py", line 89, in join
genericpath._check_arg_types('join', a, *p)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/genericpath.py", line 143, in _check_arg_types
(funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'TextIOWrapper'
Below is my code. Has anyone got any solutions I could implement, or should I kill it with fire.
import re
import os
os.mkdir ("dest")
file = open("2016-06-06_UK_BackToSchool.html").read()
text_filtered = re.sub(r'http://', '/', file)
print (text_filtered)
with open ("2016-06-06_UK_BackToSchool.html", "wt") as out_file:
print ("testtesttest")
with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)):
out_file.write(text_filtered)
os.rename("/Users/Glenn/jack/HTML_Task/src/2016-06-06_UK_BackToSchool.html", "/Users/Glenn/jack/HTML_Task/src/dest/2016-06-06_UK_BackToSchool.html")
with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)):
Here out_file if TextIOWrapper, not string.
os.path.join takes string as arguments.
Do not use keywords name as variable. file is keyword.
Do not use space in between function call os.mkdir ("dest")
try to change this:
with open ("2016-06-06_UK_BackToSchool.html", "wt") as out_file
on this:
with open ("2016-06-06_UK_BackToSchool.html", "w") as out_file:
or this:
with open ("2016-06-06_UK_BackToSchool.html", "wb") as out_file:

Importing a file based upon the path

I have a python script that exports a file using the following command in a function. It's works, but I need to import that file after exporting and loop through it.
connector.save_csv(path,'_'+"GT_Weekly"+'_'+keys)
Thereore, I've been hard coding the file name and using it with open(). However, I was wondering how I could specify the file name in the same way as specified when I saved it.
Here's the hard coded approach:
with open(path,'_'+"GT_Weekly"+'_'+keys+'.csv', 'rt') as csvfile:
csvReader = csv.reader(csvfile)
data = []
I want to take the save_csv arguments and add it to open but that doesn't work. How can I do this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Both keys and path were specified as
keys ="football"
path = "/home/abraham/Trends"
What component needs to be changed to an integer? It's not evident to me
Furthermore, when I add int,I get the following error
with int(open(path,'_'+"GT_Weekly"+'_'+keys+'.csv', 'rt')) as csvfile:
csvReader = csv.reader(csvfile)
data = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>>
You seem to think open accepts a path, a file name, and a mode; but it doesn't. The parameters are a file name, a mode, and a buffer size. The buffer size should be an integer, but you are passing 'rt'; hence, you get an error message.
I guess you want open(os.path.join(path, filename), 'rt') instead, or possibly open(path + filename, 'rt'), if the last component of path is a prefix part of the filename you want, not a directory name.

Python: Can not write to CSV file

I have this snippet of Python code:
import csv
def analyse(csvFileToRead, csvFileToWrite):
# open file to read
openedCsvFileToRead = open(csvFileToRead)
reader = csv.reader(openedCsvFileToRead)
# open file to write
openedCsvFileToWrite = open(csvFileToWrite)
writer = csv.writer(openedCsvFileToWrite)
for row in reader:
date = row[8]
if date[0] == "5":
writer.writerow(row)
# close file
openedCsvFileToRead.close()
openedCsvFileToWrite.close()
if __name__ == "__main__":
analyse("mydata.csv", "mynewdata.csv")
when run using Python 3.4 I get the following error message:
Traceback (most recent call last):
File "main.py", line 40, in <module>
analyse("mydata.csv", "mynewdata.csv")
File "main.py", line 25, in analyse
writer.writerow(row)
io.UnsupportedOperation: not writable
What Am I doing wrong?
I'm on Windows 7 64bit.
You have to open the file in write mode:
openedCSvFileToWrite = open(csvFileToWrite, "w")
Note that in Python 2.x, the docs always use 'wb', rather than 'w'.

Python, unpacking a .jar file, doesnt work

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

Categories