I am trying to write a file to a specific location, to do this I wrote the following code.
The program is in a folder on an external HDD. I have used the os.path to get the current path (I think..)
the "fileName" var is = hello
the "savePath" var is = data
When I run the code I get the following error...
IOError: [Errno 13] Permission denied: 'data\hello_23-04-2014_13-37-55.csv'
Do I need to set permissions for the file before I try to write to it? If so.. how do you do this>?
def writeData(fileName, savePath, data):
# Create a filename
thisdate = time.strftime("%d-%m-%Y")
thistime = time.strftime("%H-%M-%S")
name = fileName + "_" + thisdate + "_" + thistime + ".csv"
# Create the complete filename including the absolute path
completeName = os.path.join(savePath, name)
# Check if directory exists
if not os.path.exists(completeName):
os.makedirs(completeName)
# Write the data to a file
theFile = open(completeName, 'wb')
writer = csv.writer(theFile, quoting=csv.QUOTE_ALL)
writer.writerows(data)
I get a different error (putting permission issues aside) when I try a stripped down version of what you're doing here:
>>> import os
>>> path = "foo/bar/file.txt"
>>> os.makedirs(path)
>>> with open(path, "w") as f:
... f.write("HOWDY!")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 21] Is a directory: 'foo/bar/file.txt'
Note that when you do this:
# Check if directory exists
if not os.path.exists(completeName):
os.makedirs(completeName)
...you're creating a directory that has a name that's both the path you want (good) and the name of the file you're trying to create. Pass the pathname only to makedirs() and then create the file inside that directory when you've done that.
Related
This question already has answers here:
How to identify whether a file is normal file or directory
(7 answers)
Closed 5 years ago.
I found some example code for ClamAV. And it works fine, but it only scans a single file. Here's the code:
import pyclamav
import os
tmpfile = '/home/user/test.txt'
f = open(tmpfile, 'rb')
infected, name = pyclamav.scanfile(tmpfile)
if infected:
print "File infected with %s Deleting file." %name
os.unlink(file)
else:
print "File is clean!"
I'm trying to scan an entire directory, here's my attempt:
import pyclamav
import os
directory = '/home/user/'
for filename in os.listdir(directory):
f = open(filename, 'rb')
infected, name = pyclamav.scanfile(filename)
if infected:
print "File infected with %s ... Deleting file." %name
os.unlink(filename)
else:
print " %s is clean!" %filename
However, I'm getting the following error:
Traceback (most recent call last):
File "anti.py", line 7, in <module>
f = open(filename, 'rb')
IOError: [Errno 21] Is a directory: 'Public'
I'm pretty new to Python, and I've read several similar questions and they do something like what I did, I think.
os.listdir("DIRECTORY") returns list of all files/dir in the DIRECTORY . It is just file names not absolute paths. So, if You are executing this program from a different directory it's bound to fail.
If you are sure that everything in the directory is a file, no sub directories. You can try following,
def get_abs_names(path):
for file_name in os.listdir(path):
yield os.path.join(path, file_name)
Then ,
for file_name in get_abs_names("/home/user/"):
#Your code goes here.
The following code will go over all your directory file by file. Your error happens because you try to open a directory as if it is a file instead of entering the dir and opening the files inside
for subdir, dirs, files in os.walk(path): # walks through whole directory
for file in files:
filepath = os.path.join(subdir, file) # path to the file
#your code here
I am trying to move text files from one folder to another by reading a path from a csv file. First I create the target folder in which I want to move my files from the existing folder. I read the existing folder path from csv file. I am working on a Windows platform.
This is my code :
import os
import csv
import shutil
#csv_filename = raw_input('Enter CSV filename:')
with open('insurance_sample.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ';')
header = next(readCSV)
count = 0
for row in readCSV:
dirname = "/".join(('Sorted_Program',row[1],row[4],row[3],row[7]))
#if not os.path.exists(dirname):
#os.makedirs(dirname)
path = row[10]
moveto = dirname
print path
print moveto
print os.path.isfile(path)
files = os.listdir(path)
print files
files.sort()
for f in files:
src = path + f
dst = moveto + f
break
I am getting this error after running the code:
C:\Users\Ashwin\Desktop\p\newDir\Archives\Beta\A380_1
Sorted_Program/A380/AFR/69/Flight_Test
False
Traceback (most recent call last):
File "C:\Users\Ashwin\Desktop\p\newDir\sar.py", line 19, in <module>
files = os.listdir(path)
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\Users\\Ashwin\\Desktop\\p\\newDir\\Archives\\Beta\\A380_1/*.*
Please let me know if the question is still confusing and I will try to explain in more detail.
So it seems there are two issues here:
You are creating a directory reference with / whereas windows directories require \
Your code does not prefix the new directory structure with \
Try the following modification:
dirname = "\\" + "\\".join(('Sorted_Program',row[1],row[4],row[3],row[7]))
I am getting some error while writing contents to csv file in python
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import csv
a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']]
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
Error
Traceback (most recent call last):
File "test.py", line 10, in <module>
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
IOError: [Errno 2] No such file or directory: 'test_1/1/2013_.csv'
How to fix it and what is the error?
You have error message - just read it.
The file test_1/1/2013_.csv doesn't exist.
In the file name that you create - you use a[0][0] and in this case it result in 1/1/2013.
Probably this two signs '/' makes that you are looking for this file in bad directory.
Check where are this file (current directory - or in .test_1/1 directory.
It's probably due to the directory not existing - Python will create the file for you if it doesn't exist already, but it won't automatically create directories.
To ensure the path to a file exists you can combine os.makedirs and os.path.dirname.
file_name = 'test_'+str(a[0][0])+'_.csv'
# Get the directory the file resides in
directory = os.path.dirname(file_name)
# Create the directories
os.makedirs(directory)
# Open the file
f3 = open(file_name, 'at')
If the directories aren't desired you should replace the slashes in the dates with something else, perhaps a dash (-) instead.
file_name = 'test_' + str(a[0][0]).replace('/', '-') + '_.csv'
My instructor provided the following code, but it is not working on OS X when run from command line.
file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
fout = open(file_name, 'w')
Error message:
Traceback (most recent call last):
File "write_a_poem_to_file.py", line 12, in <module>
fout = open(file_name, 'w')
IOError: [Errno 2] No such file or directory: 'data/poem1.txt'
I have been writing Python since before I got to the class and having done a little research, it think you need to import the os module to create a directory.
Then you can specify that you want to create a file in that directory.
I believe you might also have to switch into that directory before accessing files.
I may be wrong, and I am wondering if I am missing another issue.
As stated by #Morgan Thrapp in the comments, the open() method won't create a folder for you.
If the folder /data/ already exists, it should work fine.
Otherwise you'll have to check if the folder exists, if not, then create the folder.
import os
if not os.path.exists(directory):
os.makedirs(directory)
So.. your code:
file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
fout = open(file_name, 'w')
Became something like this:
import os
folder = 'data/'
if not os.path.exists(folder):
os.makedirs(folder)
filename = raw_input('Enter the name of your file: ')
file_path = folder + filename + '.txt'
fout = open(file_path, 'w')
Check if folder "data" does not exist. If does not exist you have to create it:
import os
file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
if not os.path.exists('data'):
os.makedirs('data')
fout = open(file_name, 'w')
import sys
import os
import re
import ftplib
os.system('dir /S "D:\LifeFrame\*.jpg" > "D:\Python\placestogo.txt"') #this is where to search.
dat = open('placestogo.txt','r').read()
drives = re.findall(r'.\:\\.+.+',dat)
for i in range(len(drives)):
path = drives[i]
os.system('dir '+ path +'\*.jpg > D:\python\picplace.txt')
picplace = open('picplace.txt','r').read()
pics = re.findall(r'\w+_\w+.\w+..jpg|IMG.+|\w+.jpg',picplace)
for i in range(len(pics)):
filename = pics[i]
ftp = ftplib.FTP("localhost")
print ftp.login("xxxxxxxx","xxxxxxxx")
ftp.cwd("/folder")
myfile = open(path,"rb")
print ftp.storlines('STOR ' + filename, myfile)
print ftp.quit()
sys.exit()
i am trying to copy all of those files to my ftp server but it gives me that error:
d:\Python>stealerupload.py
230 Logged on
Traceback (most recent call last):
File "D:\Python\stealerupload.py", line 22, in <module>
myfile = open(path,"rb")
IOError: [Errno 22] invalid mode ('rb') or filename: '"D:\\LifeFrame"'
any one knows where is the problem ? I am running as administrator and folder should have permissions
The error seems pretty obvious. You are trying to open a directory path, which is neither possible nor what you actually want to do. This bit:
for i in range(len(drives)):
path = drives[i]
...
for i in range(len(pics)):
...
myfile = open(path,"rb")
Inside the loop you are setting path to be one of your drives elements. each of these items appears to be a directory path. Then you try to open path later, which is a directory path and not a file.
In the error message, it shows '"D:\\LifeFrame"', which to me looks like you have extra quotes in path. Try adding print path to see what its value is.
Maybe you want to upload data from filename to your server, not from path, in which case Python showed in the error message is where the bug is: you should be opening filename instead.