Copying a file to a path, with Python [duplicate] - python

This question already has answers here:
How to copy a file along with directory structure/path using python? [duplicate]
(2 answers)
Closed 8 years ago.
I want to copy a certain file to a specified path. This specified path has many hierarchies of directories which do not exist in advance and need to get created during copying.
I tried shutil.copy* functions but they all seem to require that the directory at destination path is pre-created.
Is there any functions that sets up these directories as required and copies the file?
Example usage:
copy_file('resources/foo.bar', expanduser('~/a/long/long/path/foo.bar'))

You can use os.makedirs to recursively create the arborescence you need, then use shutil.copy.
target_dir = os.path.expanduser('~/a/long/long/path')
os.makedirs(target_dir)
shutil.copy('resources/foo.bar', os.path.join(target_dir, 'foo_bar'))
That way, you decompose the problem in manageable tasks (creation then copy), which lets you handle the case where the creation of the directories crashes (following the 'explicit is better than implicit').

Related

How to get all files in a directory? [duplicate]

This question already has answers here:
List only files in a directory?
(8 answers)
how to check if a file is a directory or regular file in python? [duplicate]
(4 answers)
Closed 2 months ago.
I have a directory and need to get all files in it, but not subdirectories.
I have found os.listdir(path) but that gets subdirectories as well.
My current temporary solution is to then filter the list to include only the things with '.' in the title (since files are expected to have extensions, .txt and such) but that is obviously not optimal.
We can create an empty list called my_files and iterate through the files in the directory. The for loop checks to see if the current iterated file is not a directory. If it is not a directory, it must be a file.
my_files = []
for i in os.listdir(path):
if not os.path.isdir(i):
my_files.append(i)
That being said, you can also check if it is a file instead of checking if it is not a directory, by using if os.path.isfile(i).
I find this approach is simpler than glob because you do not have to deal with any path joining.

How can I know the size of a file using a recursive program? [duplicate]

This question already has answers here:
Calculating a directory's size using Python?
(33 answers)
Closed 2 years ago.
I have to make a program that measures the size of a given directory by using recursivity. I need to use the OS module. When I used
os.path.getsize()
The response was 0 bytes, which makes no sense.
You need to mention the path in the argument of a getsize function.
So it would look like:
os.path.getsize(<path_of_file>)
If you are doing that already and interested in the size of a folder, you can add size of the files in the folder iteratively.
sum(os.path.getsize(f) for f in os.listdir(<path_of_the_folder>) if os.path.isfile(f))
I get your question, the same problem i also got, you can visit here for ans : https://github.com/ASHWIN990/sizeof/blob/master/sizeof
I have made a Pythton script which find the size of file and directories recurcively

Use os.listdir to show directories only [duplicate]

This question already has answers here:
How to list only top level directories in Python?
(21 answers)
Closed 2 years ago.
How can I bring python to only output directories via os.listdir, while specifying which directory to list via raw_input?
What I have:
file_to_search = raw_input("which file to search?\n>")
dirlist=[]
for filename in os.listdir(file_to_search):
if os.path.isdir(filename) == True:
dirlist.append(filename)
print dirlist
Now this actually works if I input (via raw_input) the current working directory. However, if I put in anything else, the list returns empty. I tried to divide and conquer this problem but individually every code piece works as intended.
that's expected, since os.listdir only returns the names of the files/dirs, so objects are not found, unless you're running it in the current directory.
You have to join to scanned directory to compute the full path for it to work:
for filename in os.listdir(file_to_search):
if os.path.isdir(os.path.join(file_to_search,filename)):
dirlist.append(filename)
note the list comprehension version:
dirlist = [filename for filename in os.listdir(file_to_search) if os.path.isdir(os.path.join(file_to_search,filename))]

How to find what files are in a folder [duplicate]

This question already has answers here:
Directory-tree listing in Python
(21 answers)
Closed 9 years ago.
I am writing a function that is recieving a folder path as an arguemnt. I want her to add into a dictionary what's inside the folder (like dir in CMD)
How can I do this ?
Thank you in advance,
Iliya
import os
print os.listdir('/tmp')
Similar Topics:
Directory listing in Python
Also, I use os.path and glob a lot while manipulating file system path.
You might want to check it out.

How to create new folder? [duplicate]

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)

Categories