If I have the following file:
file = '/Users/david542/Desktop/work.txt'
I can use os.path.basename(file) to get the file name.
What command would I use to get the directory of the file (i.e., to get "/Users/david542/Desktop") ?
os.path.dirname(file) returns the directory of the passed file name. Alternatively, you can use os.path.split(file) which will give you a tuple containing the directory name and the file name in one call.
>>> os.path.dirname(os.path.realpath('/Users/david542/Desktop/work.txt'))
os.path.dirname(file) will yield directory name.
import os
print(os.path.dirname("c:/windows/try.txt"))
I think you're searching for os.path.dirname. Otherwise you could use os.path.split which returns the path and the filename in a tuple.
Related
I can't see what i am doing wrong here
import os
def check():
path = "d://Mu$ic//"
for file in os.listdir(path):
if file.endswith("*.mp3"):
print (os.path.join(path,file))
check()
The output doesn't show up , any idea what am i doing wrong?
Omitting the * should work, since endswith matches on a string suffix (as opposed to *.mp3 which is a wildcard):
file.endswith(".mp3"):
Also, you could replace // with just /.
Is only mp3 files in the folder? If so why do you need the check for endswith? If mp3 is the only file type in that folder it should be able to return them without checking if they end with .mp3. Unless you have other file types in there then you would need the endswith check. I did your code here without endswith and it returned every .wav file in the folder.
If you are using python 3, you also can use glob
import glob
_path = '{0}**/*.mp3'.format("d://Mu$ic//")
file_lst = glob.glob(_path, recursive=True)
print(file_lst)
['2.mp3', '3.mp3', ...]
I'm using python's zipfile module.
Having a zip file located in a path of:
/home/user/a/b/c/test.zip
And having another file created under /home/user/a/b/c/1.txt
I want to add this file to existing zip, I did:
zip = zipfile.ZipFile('/home/user/a/b/c/test.zip','a')
zip.write('/home/user/a/b/c/1.txt')
zip.close()`
And got all the subfolders appears in path when unzipping the file, how do I just enter the zip file without path's subfolders?
I tried also :
zip.write(os.path.basename('/home/user/a/b/c/1.txt'))
And got an error that file doesn't exist, although it does.
You got very close:
zip.write(path_to_file, os.path.basename(path_to_file))
should do the trick for you.
Explanation: The zip.write function accepts a second argument (the arcname) which is the filename to be stored in the zip archive, see the documentation for zipfile more details.
os.path.basename() strips off the directories in the path for you, so that the file will be stored in the archive under just it's name.
Note that if you only zip.write(os.path.basename(path_to_file)) it will look for the file in the current directory where it (as the error says) does not exist.
import zipfile
# Open a zip file at the given filepath. If it doesn't exist, create one.
# If the directory does not exist, it fails with FileNotFoundError
filepath = '/home/user/a/b/c/test.zip'
with zipfile.ZipFile(filepath, 'a') as zipf:
# Add a file located at the source_path to the destination within the zip
# file. It will overwrite existing files if the names collide, but it
# will give a warning
source_path = '/home/user/a/b/c/1.txt'
destination = 'foobar.txt'
zipf.write(source_path, destination)
I have tried to append a record on the next line in the file using the following code(please note that the file has been created already). But, it does not insert any records at all. The file remains empty.
with open(utmppath+'/'+tmpfile, "a") as myfile:
myfile.write(record+'\n')
myfile.close()
Any suggestion would be great. Thanks
Check additionally if you set your path correctly:
import os
path = utmppath+'/'+tmpfile
assert os.path.isfile(path), path
The assertion checks if the file exists and raises an AssertionError if you used a wrong path. Additionally the used path is included in the error message thanks to the variable
after the comma.
Additionally I recommend you to join files with the help of os.path.join and os.path.abspath. os.path.join concatenates path strings correctly for you and os.path.abspath creates an absolute path.
path = os.path.join(utmppath, tmpfile)
Let's say the wished file is in the same directory like your script and called your_output.txt - you can use this:
path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'your_output.txt'))
By the way, __file__ gives you the name of your script file.
I'm trying to get the list of files in a particular directory and count the number of files in the directory. I always get the following error:
WindowsError: [Error 3] The system cannot find the path specified: '/client_side/*.*'
My code is:
print len([name for name in os.listdir('/client_side/') if os.path.isfile(name)])
I followed the code example given here.
I am running the Python script on Pyscripter and the directory /client_side/ do exists. My python code is in the root folder and has a sub-folder called "client_side". Can someone help me out on this?
This error occurs when you use os.listdir on a path which does not refer to an existing path.
For example:
>>> os.listdir('Some directory does not exist')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
WindowsError: [Error 3] : 'Some directory does not exist/*.*'
If you want to use os.listdir, you need to either guarantee the existence of the path that you would use, or use os.path.exists to check the existence first.
if os.path.exists('/client_side/'):
do something
else:
do something
Suppose your current working directory is c:\foobar, os.listdir('/client_side/') is equivalent to os.listdir('c:/client_side'), while os.listdir('client_side/') is equivalent to os.listdir('c:/foobar/client_side'). If your client_side directory is not in the root, such error will occur when using os.listdir.
For your 0 ouput problem, let us recall os.listdir(path)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
and os.path.isfile(path).
Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
listdir returns neither the absolute paths nor relative paths, but a list of the name of your files, while isfile requires path. Therefore, all of those names would yield False.
To obtain the path, we can either use os.path.join , concat two strings directly.
print ([name for name in os.listdir(path)
if os.path.isfile(os.path.join(path, name))])
Or
print ([name for name in os.listdir('client_side/')
if os.path.isfile('client_side/' + name)])
I decided to change the code into:
def numOfFiles(path):
return len(next(os.walk(path))[2])
and use the following the call the code:
print numOfFiles("client_side")
Many thanks to everyone who told me how to pass the windows directory correctly in Python and to nrao91 in here for providing the function code.
EDIT: Thank you eryksun for correcting my code!
Two things:
os.listdir() does not do a glob pattern matching, use the glob module for that
probably you do not have a directory called '/client_side/*.*', but maybe one
without the . in the name
The syntax you used works fine, if the directory you look for exists, but there is no directory called '/client_side/.'.
In addition, be careful if using Python 2.x and os.listdir, as the results on windows are different when you use u'/client_side/' and just '/client_side'.
You can do just
os.listdir('client_side')
without slashes.
As I can see a WindowsError, Just wondering if this has something to do with the '/' in windows ! Ideally, on windows, you should have something like os.path.join('C:','client_side')
You want:
print len([name for name in os.listdir('./client_side/') if os.path.isfile(name)])
with a "." before "/client_side/".
The dot means the current path where you are working (i.e. from where you are calling your code), so "./client_side/" represents the path you want, which is specified relatively to your current directory.
If you write only "/client_side/", in unix, the program would look for a folder in the root of the system, instead of the folder that you want.
If you just want to see all the files in the directory where your script is located, you can use os.path.dirname(sys.argv[0]). This will give the path of the directory where your script is.
Then, with fnmatch function you can obtain the list of files in that directory with a name and/or extension specified in the filenamevariable.
import os,sys
from fnmatch import fnmatch
directory = os.path.dirname(sys.argv[0]) #this determines the directory
file_name= "*" #if you want the python files only, change "*" to "*.py"
for path, subdirs, files in os.walk(directory):
for name in files:
if fnmatch(name, file_name):
print (os.path.join(path, name))
I hope this helps.
Checking for existence is subject to a race. Better to handle the error (beg forgiveness instead of ask permission). Plus, in Python 3 you can suppress errors. Use suppress from contextlib:
with suppress(FileNotFoundError):
for name in os.listdir('foo'):
print(name)
Given a local directory structure of /foo/bar, and assuming that a given path contains exactly one file (filename and content does not matter), what is a reasonably fast way to get the filename of that single file (NOT the file content)?
1st element of os.listdir()
import os
os.listdir('/foo/bar')[0]
Well I know this code works...
for file in os.listdir('.'):
#do something
you can also use glob
import glob
print glob.glob("/path/*")[0]
os.path.basename will return the file name for you
so you can use it for the exact one file by adding your file path :
os.path.basename("/foo/bar/file.file")
or you can run through the files in the folder and read all names
file_src = "/foo/bar/"
for x in os.listdir(file_src):
print(os.path.basename(x))