This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 8 years ago.
I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.
Suppose I have given folder path like "C:\Program Files\alex" and alex folder doesn't exist then program should create alex folder and should put output information in the alex folder.
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
You probably want os.makedirs as it will create intermediate directories as well, if needed.
import os
#dir is not keyword
def makemydir(whatever):
try:
os.makedirs(whatever)
except OSError:
pass
# let exception propagate if we just can't
# cd into the specified directory
os.chdir(whatever)
Related
This question already has answers here:
How to delete the contents of a folder?
(26 answers)
Closed 1 year ago.
I am trying to create a python script to help clean up a folder that I create with powershell. This is a directory that contains folders named after the users for them to put stuff into.
Once they leave our site, their folder remains and for all new staff who come a folder gets created. This means that we have over 250 folders but only 100 active staff. I have a test folder that I am using so that I can get the script working and then add in extra bits like moving the directories to an old location, and then deleting them based on age. But at the moment I am working on the delete portion of the script. So far I have the below script, it runs with no errors, but it doesn't actually do anything and I am failing to see why..
It should be reading a csv file that I have of all current staff members, and then comparing that to the folders located in the filepath and then removing any folders that dont match the names in the CSV file.
The CSV file is generated from powershell using the same script that I used to create them.
import os
import pandas as pd
path = "//servername/Vault/Users$"
flist = pd.read_csv('D:/Staff List.csv')
file_name = flist['fileName'].tolist()
for fileName in os.listdir(path):
#If file is not present in list
if fileName not in file_name:
#Get full path of file and remove it
full_file_path = os.path.join(path, fileName)
os.remove(full_file_path)
Use shutil and recursively remove all old user directories and their contents.
import shutil
PATH = 'D:/user/bin/old_dir_to_remove'
shutil.rmtree(PATH)
I want to make subfolder in another folder. I can make main folder but I don't know how to make other folder in this.
import os
fol = os.makedirs('2020')
Using makedirs you can do at once
os.makedirs('2020/subfolder/subsubfolder')
and it should create 2020, next 2020/subfolder, and next 2020/subfolder/subsubfolder
If you already created folder 2020 then you can also use path with 2020/ at the beginning to create subfolder
os.makedirs('2020/subfolder')
or you can change folder and then create subfolder without using 2020/
os.chdir('2020')
os.makedirs('subfolder')
BTW: probably since Python 3.6 or 3.7 you can use exist_ok=True to skip creating if folder already exist.
os.makedirs('2020/subfolder', exist_ok=True)
Without exist_ok=True it would raise error if folder already exist. And you would need this:
if not os.path.exists('2020/subfolder'):
os.makedirs('2020/subfolder')
This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 2 years ago.
I hope everyone is staying safe and sound.
Could you please help me with file name change in certain directory?
I am writing a script for RDA to download documents from this website, and when I download these files from this website, file names do not have pattern, it is completely random. So I want to rename these files into certain pattern.
For example,
1st downloaded file name: filedownload.pdf
rename to: 1234567.pdf
2nd downloaded file name: extractpages.pdf
rename to: 1234568.pdf
new names are set in parameter so that part is good but as I don't know what downloaded file name will be, I can't change this file name into new name.
So what I had in mind is for each downloaded file, put it in this folder without any files, and whenever any file is located in this folder, it renames the file and put it in different folder.
Below is the code I wrote;
filepath = "originalFilePath/downloadedfile.pdf"
if os.path.isfile(filepath):
os.rename(r'originalFilePath/downloadedfile.pdf',
'newFilePath' + str(parameter['search_number']) + '.pdf')
But I would like to change file names no matter what the downloaded file name is.
Please help, thank you very much!!
I think your idea is quite correct.
First, you will list all file name in a folder before downloading anything, store that list in a variable, let's say current_files. Then you start downloading files from the web, after that, you list all the file name again and store in the second list. Now you will compare 2 lists and know what files are new (just downloaded). Then you just simply loop over these new files and rename it in a pattern that you want. I will add code in a minute
import glob
current_files = glob.glob("/path/Downloads/*.pdf")
# ['path/Downloads/abc.pdf', 'path/Downloads/xyz.pdf']
# your code to download files from the web
new_files = set(glob.glob("/path/Downloads/*.pdf")) - set(current_files)
# ['path/Downloads/just_downloaded1.pdf', 'path/Downloads/just_downloaded2.pdf']
for file in new_files:
#do the rename code here to your new files
You question is not totally clear.
Anyway I think you have an issue with your code, you have to add / after newFilePath.
Use os.renames(old, new).
os.renames(old, new)
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs().
References
https://docs.python.org/3/library/os.html
This question already has answers here:
How can I list the contents of a directory in Python?
(8 answers)
Closed 4 years ago.
Is it possible to output the contents of a folder in python ?
If, say you had a function and you would pass the folder path to its argument?
What would be the simplest way for a beginner to take?
By "simplest" I mean, without using any modules.
Note
Google usually leads me to stackoverflow. Plus I am not looking for generic answers. I am looking for insight based on experience and wit, which I can only find here.
You could use os.listdir() to look at the contents of a directory. It takes the path as an argument, for example:
import os
directory = os.listdir('/')
for filename in directory:
print(filename)
prints this for me:
bin
home
usr
sbin
proc
tmp
dev
media
srv
etc
lib64
mnt
boot
run
var
sys
lib
opt
root
.dockerenv
run_dir
How about listdir? Let's try like this way-
import os
def ShowDirectory:
return os.listdir("folder/path/goes/here")
ShowDirectory()
With function.
def ListFolder(folder):
import os
files = os.listdir(folder)
print(*files,sep="\n")
Please use google first next time...it seems you are looking for this:
How can I list the contents of a directory in Python?
The accepted answer there:
import os
os.listdir("path") # returns list
This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 5 years ago.
so I want this to be independent of the computer the code is used on, so I want to be able to create a directory in the current directory and save my plots to that new file. I looked at some other questions and tried this (I have two attempts, one commented out):
import os
from os import path
#trying to make shift_graphs directory if it does not already exist:
if not os.path.exists('shift_graphs'):
os.mkdirs('shift_graphs')
plt.title('Shift by position on '+str(detector_num)+'-Detector')
#saving figure to shift_graphs directory
plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
print "plot 5 done"
plt.clf
I get the error :
AttributeError: 'module' object has no attribute 'mkdirs'
I also want to know if my idea of saving it in the directory will work, which I haven't been able to test because of the errors I've been getting in the above portion.
os.mkdirs() is not a method in os module.
if you are making only one direcory then use os.mkdir() and if there are multiple directories try using os.makedirs()
Check Documentation
You are looking for either:
os.mkdir
Or os.makedirs
https://docs.python.org/2/library/os.html
os.makedirs makes all the directories, so if I type in shell (and get nothing):
$ ls
$ python
>>> import os
>>> os.listdir(os.getcwd())
[]
>>> os.makedirs('alex/is/making/a/path')
>>> os.listdir(os.getcwd())
['alex']
It has made all the directories and subdirectories. os.mkdir would throw me an error, because there is no "alex/is/making/a" directory.