I definitely have placed some files in my trash bin on my Mac but for some reason my code is printing an empty array [] - here is my code in my python file:
import os
from distutils.dir_util import copy_tree
from datetime import datetime
import shutil
bin_location = "/Users/nick/.Trash"
bin_files = os.listdir(bin_location)
for f in bin_files:
print(f)
print(os.listdir('/Users/nick/.Trash'))
I’m using VSCode and have given permission in my system settings to allow the program to access the .Trash directory (to fix a permissions error I initially had). Is there something obvious that I’m doing wrong? I cannot see why it is not listing the files in the bin.
Related
I need to prepare script which user backups in Python (I'm the beginner in Python) and I have a problem with copy files beetwen catalogs. When I run script, I get this error:
*PermissionError: [Errno 13] Permission denied: 'C:/Users/User/Documents/PythonProjects\\New catalog'*
New catalog is a dir which is in PythonProjects dir.
What I did:
I checked permissions in catalog PythonProjects (User has persmissions to read/save/modify this catalog). I dont' know what I can to do next step to verify this issue. I saw many threads and any solution doesn't fix my issue.
This is my code:
import shutil
import os
sourceCatalog = "C:/Users/User/Documents/PythonProjects"
destinationCatalog = "D:/BACKUP_NEW"
files = os.listdir(sourceCatalog)
for filesNames in files:
shutil.copy2(os.path.join(sourceCatalog, filesNames), destinationCatalog)
Thank you for potential tips.
Python's shutil module offers several functions to copy files or directories. As opposed to the cp or copy commands, shutil.copy[2] however, is not a one size fits all solution.
Namely, shutil.copy2 will refuse to copy a directory and give the "permission denied" error (at least on Windows). To copy a directory - or rather an entire directory tree - shutil.copytree is the right command.
So the fixed code reads:
import shutil
import os
sourceCatalog = "C:/Users/User/Documents/PythonProjects"
destinationCatalog = "D:/BACKUP_NEW"
files = os.listdir(sourceCatalog)
for filesNames in files:
shutil.copytree(os.path.join(sourceCatalog, filesNames), destinationCatalog)
I want to create files with the extension .txt, .csv, .bin, etc. so the ideal would be with import os I think or if there is some other better way.
But I don't want to save those in the DB they are to consult the once or sporadically, that is, locally are uploaded to the server and then it is replaced and that's it.
In a simple way, I create the files I need, upload them and replace them when I need something that will not be so common.
The directory for these local files would be /app/files/.
I managed to create files using directory path, something like
imports
def createFile (self, my_data, nameFile):
directory = "./my_app/folder/" + nameFile + ".txt" # PATH directory
my_File = open (directory, "w")
my_File.write (my_data)
my_File.close ()
return true
In itself the important thing is import os and write well the directory where the file will be created. No need to modify anything else.
In the Django documentation I saw something in the import of some classes but in my case this was enough, on the other hand now that I write this answer from django.core.files import File which as seen is the equivalent of import os
I tried to use these
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.core.files.storage import FileSystemStorage
As I do not have time and I had problems with these, I went with the easy
PS: maybe then use from django.core.files import File instead of import os as it seems to be the same, if so I update the answer.
I m currently using the shutil library to zip the file,
Current folder structure
In the d drive
A_zipdirectory.py for running the python code
A_dest folder to be zipped
A_backup folder that will stored the zipped folder
Python code
import shutil
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
zip_loc = 'D:/A_dest'
zip_dest = 'D:/A_backup'
shutil.make_archive(base_dir=zip_loc, root_dir=zip_loc, format='zip',
base_name=zip_dest)
When i run this, No error occurs, but i cannot zip and move the file to the backup folder, Any idea? Many thanks
try to add logger and see what happening. (you can deliver logger to shutil.make_archive)
sorry it answer and not comment, i can't comment yet
I've been working on a project where I need to import csv files, previously the csv files have been in the same working directory. Now the project is getting bigger so for security and organizational resaons I'd much prefer to keep them in a different directory.
I've had a look at some other questions asking similar things but I couldn't figure out out how to apply them to my code as each time I tried I kept getting the same error message mainly:
IOError: [Errno 2] No such file or directory:
My original attempts all looked something like this:
import csv # Import the csv module
import MySQLdb # Import MySQLdb module
def connect():
login = csv.reader(file('/~/Projects/bmm_private/login_test.txt'))
I changed the path within several times as well by dropping the first / then then the ~ then the / again after that, but each time I got the error message. I then tried another method suggested by several people by importing the os:
import os
import csv # Import the csv module
import MySQLdb # Import MySQLdb module
def connect():
path = r'F:\Projects\bmm_private\login_test.txt'
f = os.path.normpath(path)
login = csv.reader(file(f))
But I got the error message yet again.
Any help here would be much appreciated, if I could request that you use the real path (~/Projects/bmm_private/login_test.txt) in any answers you know of so it's very clear to me what I'm missing out here.
I'm pretty new to python so I may struggle to understand without extra clarity/explanation. Thanks in advance!
The tilde tells me that this is the home folder (e.g. C:\Users\<username> on my Windows system, or /Users/<username> on my Mac). If you want to expand the user, use the os.path.expanduser call:
full_path = os.path.expanduser('~/Projects/bmm_private/login_test.txt')
# Now you can open it
Another approach is to seek for the file in relative to your current script. For example, if your script is in ~/Projects/my_scripts, then:
script_dir = os.path.dirname(__file__) # Script directory
full_path = os.path.join(script_dir, '../bmm_private/login_test.txt')
# Now use full_path
How can I set the current path of my python file "myproject.py" to the file itself?
I do not want something like this:
path = "the path of myproject.py"
In mathematica I can set:
SetDirectory[NotebookDirectory[]]
The advantage with the code in Mathematica is that if I change the path of my Mathematica file, for example if I give it to someone else or I put it in another folder, I do not need to do anything extra. Each time Mathematica automatically set the directory to the current folder.
I want something similar to this in Python.
The right solution is not to change the current working directory, but to get the full path to the directory containing your script or module then use os.path.join to build your files path:
import os
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
# then:
myfile_path = os.path.join(ROOT_PATH, "myfile.txt")
This is safer than messing with current working directory (hint : what would happen if another module changes the current working directory after you did but before you access your files ?)
I want to set the directory in which the python file is, as working directory
There are two step:
Find out path to the python file
Set its parent directory as the working directory
The 2nd is simple:
import os
os.chdir(module_dir) # set working directory
The 1st might be complex if you want to support a general case (python file that is run as a script directly, python file that is imported in another module, python file that is symlinked, etc). Here's one possible solution:
import inspect
import os
module_path = inspect.getfile(inspect.currentframe())
module_dir = os.path.realpath(os.path.dirname(module_path))
Use the os.getcwd() function from the built in os module also there's os.getcwdu() which returns a unicode object of the current working directory
Example usage:
import os
path = os.getcwd()
print path
#C:\Users\KDawG\Desktop\Python