I am attempting to write a class to create an excel sheet using my Django Models. I have created the following class:
class workBook(object):
def __init__(self, title, data):
path = '\\workbooks\\' + title + '.xlsx'
print(os.path.normpath(path))
self.workbook = xlsxwriter.Workbook(os.path.normpath(path))
newWorkSheet(self.workbook, data)
self.workbook.close()
The method creates the workbook with the proper path but when I close it I get the following error:
[Errno 2] No such file or directory: '\\workbooks\\Test.xlsx'
I know this is because of the double "\" but I dont know how to send the correct path to the close method. I also know the rest of my class works because it does not throw this error when I simply put the file name and not a full directory.
Thank you!
I fixed it by just using "/" instead of "\" in a custom path.
Related
There are answers to the window version. but not mac.
I have searched google but no appropriate result
let say I want to create a shortcut to google.com on desktop, then we could run the python function
createShortcut("www.google.com","~/Desktop")
what could be the function body?
You can create a macos .url file inside the function. It is formatted as follows:
[InternetShortcut]
URL=http://www.yourweb.com/
IconIndex=0
Here is a sample implementation:
import os
def createShortcut(url, destination):
# get home directory if ~ in destination
if '~' in destination:
destination = destination.replace('~', os.path.expanduser("~"))
# macos .url file format
text = '[InternetShortcut]\nURL=https://{}\nIconIndex=0'.format(url)
# write .url file to destination
with open(destination + 'my_shortcut.url', 'w') as fw:
fw.write(text)
return
createShortcut("www.google.com", '~/Desktop/')
I'm using Google Drive API in Python to make archiving of my files.
However i am having an issue renaming the copy of my original file.
The title of my new file defaults to
'Copy of + original filename'
However I want my new file's name is
'original filename + current date'
I can't find how to change the title configure in the copied code or rename the new file I have copied.
The copy code I used is:
service.files().copy(fileId=original_file_id).execute()
Does anyone know how to rename a file title in Python? Or any alternate method will also be welcome.
I'm unsure how exactly you want the date and the copied file name to be formatted, but you can do the following:
Retrieve the name of the original file via Files: get.
Copy the file via Files: copy, and retrieve the copied file ID.
Build the desired name, using the name of the original file and whatever date you have.
Update the copy with the new name, via Files: update.
Code snippet:
from datetime import date
def copyFile(service, fileId):
fileName = service.files().get(fileId=fileId).execute()["name"]
copyId = service.files().copy(fileId=fileId).execute()["id"]
currentDate = date.today()
copyName = "{} | {}".format(fileName, currentDate)
body = { "name": copyName }
service.files().update(fileId=copyId, body=body).execute()
Please note i am not a python developer this code is a wild guess on my part you will need to fix it.
The Files.copy has a parameter called name which you can send with the request. I am not sure how the optional parameters are sent with the python libray. The only issue i see with this is that you will need to do a file.get first so that you have the current name of the file that you can use to pass to this method.
request = service.files().copy(fileId=original_file_id);
request.Name = 'original file name + current date';
response = request.execute();
I want to create a tool called unifile for saving and opening files
like this unifile.open.yaml("file.yaml").
This is my structure:
unifile
|
├-open
| └--__init__.py
|
└-save
└--__init__.py
Code that call my module:
import unifile
a = unifile.open.yaml("file.yaml")
open/init.py
import yaml
class open():
def yml(self, file_path):
try:
with open(file_path, "r", encoding="utf-8") as yaml_conf:
yaml_file = yaml.safe_load(yaml_conf)
return yaml_file
except OSError:
print("Can't load yaml")
1 error if I import unifile always say:
module unifile has no atribute open
2 error in __init__.py I can't open file
[pylint] Context manager 'open' doesn't implement enter and exit. [not-context-manager]
here adding solution to ur problem, make your project structure like this.
add unifile/__init__.py file in the unifile itself not in other modules.
then unifile/open/_open.py file content
import yaml
class Open():
def __init__(self):
pass
def yml(self, file_path):
try:
with open(file_path, "r", encoding="utf-8") as yaml_conf:
yaml_file = yaml.safe_load(yaml_conf)
return yaml_file
except OSError:
print("Can't load yaml")
content of the unifile/__init__.py file
from .open._open import Open
in terminal run the program like this
Also, It is better to create a object element first then proceed ahead.
Two issues, two answers.
First, you should add an init file in unifile. With this, Python will understand that unifile is a package with a sub package.
Second, open is a built-in function and you overwrite it by calling your class open. Change your class name and it should work.
You are getting this error because unifile is not a package. There isn't any init.py file at the top level same as open and save. You also cannot call open.yml directly, because open is a class in package open, so either you will have to import open from open, create its instance and then call iml on that instance.
from open import open
a = open().yml('file.yml')
You are getting this error, because you are trying to override an existing keyword in Python open which you should strictly prohibit doing. So you should name your class anything except a reserved keyword.
Flask-uploads has something called UploadSet which is described as a "single collection of files". I can use this upload set to save my file to a predefined location. I've defined my setup:
app = Flask(__name__)
app.config['UPLOADS_DEFAULT_DEST'] = os.path.realpath('.') + '/uploads'
app.config['UPLOADED_PHOTOS_ALLOW'] = set(['png', 'jpg', 'jpeg'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
# setup flask-uploads
photos = UploadSet('photos')
configure_uploads(app, photos)
#app.route('/doit', method=["POST"])
def doit():
myfile = request.files['file']
photos.save(myfile, 'subfolder_test', 'filename_test')
return ''' blah '''
This should save to ./uploads/photos/subfolder_test/filename_test.png
My test image is: 2.6MB and is a png file. When I upload this file, I get the error:
...
File "/home/btw/flask/app.py", line 57, in doit
photos.save(myfile, 'subfolder_test', 'filename_test')
File "/usr/local/lib/python2.7/dist-packages/flaskext/uploads.py", line 388, in save
raise UploadNotAllowed()
UploadNotAllowed
However it doesn't say exactly what is not allowed. I have also tried removing all constraints, but the app still throws this error. Why?
EDIT:
Okay, so I figured out that it's not actually the constraints that is causing the problem. It is the subfolder and/or the filename that is causing the problem:
# This works
# saves to: ./uploads/photos/filename_test.png
photos.save(myfile)
But I want to save to my custom location ./uploads/photos/<custom_subdir>/<custom_filename>. What is the correct way of doing this?
You need to give your filename_test the extension as well
photos.save(myfile, 'subfolder_test', 'filename_test.png')
The UploadSet checks the extension on the new file name and will throw the exception if the new extension is not allowed.
Since you are not giving the new file an extension, it does not recognize it.
You can add a dot to file's name, then the file's extension will be appended.
photos.save(myfile, 'subfolder_test', 'filename_test' + '.')
save(storage, folder=None, name=None)
Parameters:
storage – The uploaded file to save.
folder – The subfolder within the upload set to save to.
name – The name to save the file as. If it ends with a dot, the file’s extension will be appended to the end.
Currently, I am using the following method for uploading files (via HTML form) in Pyramid.
if request.params.get('form.submitted'):
upload_directory = os.getcwd() + '/myapp/static/uploads/'
my_file = request.POST.get('thumbnail')
saved_file = str(upload_directory) + str(my_file.filename)
perm_file = open(saved_file, 'w')
shutil.copyfileobj(my_file.file, perm_file)
my_file.file.close()
perm_file.close()
I am just wondering, is this a good way of saving file uploads, are there any security concerns with my method? How else can I improve my method. Thanks.
You'll want to use something like werkzug's safe_join rather than just adding the upload directory to the given file name. An attacker could create a POST with a filename of ../../../some/important/path and cause this script to overwrite some file outside of your upload_directory.