This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 2 years ago.
so there are alot of files with .lnk extension in the start menu folder C:\ProgramData\Microsoft\Windows\Start Menu\Programs i want to print all those file names so i tried this code:
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive = True):
print(file)
it prints the link to the files, but i want to print only the file names with the extension of ".lnk"
Convert the absolute path to list then take the last element from the list. See the below code.
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive=True):
print(os.path.split(file)[-1])
Related
This question already has answers here:
Regular expression usage in glob.glob?
(4 answers)
Closed 4 years ago.
In a directory i have multiple files. but i want to fetch only few csv files with particular pattern.
Example
files in a directory: abc.csv, xyz.csv, uvw.csv, sampl.csv, code.py, commands.txt, abc_1.csv, sam.csv, xyz_1.csv, uvw_1.csv, mul.csv, pp.csv......
I need to fetch csv filenames : abc.csv , xyz.csv, uvw.csv, abc_1.csv, xyz_1.csv, uvw_1.csv, abc_2.csv , xyz_2.csv, uvw_2.csv,.... (sometimes more files with change in just the number in filename like abc_3.csv)
In python we can fetch the files using
files = glob.glob("*.csv")
But for the above requirement how to modify the above line or any other efficient way of doing it
Using Regex.
Ex:
import glob
import os
import re
for filename in glob.glob(r"Path\*.csv"):
if re.match(r"[a-z]{3}(_\d*)?\.csv", os.path.basename(filename)):
print(filename)
This question already has answers here:
Python error os.walk IOError
(2 answers)
Closed 4 years ago.
I am trying to create a list of paths for multiple files with the same name and format from different folders. I tried doing this with os.walk with the following code:
import os
list_raster = []
for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
for file in files:
if "woody02.tif" in file:
list_raster.append(files)
print (list_raster)
However, this only gives me two things
the file name
All file names in each folder
I need the the full location of only the specified 'woody02.txt' in each folder.
What am I doing wrong here?
The full path name is the first item in the tuples in the list returned by os.walk, so it is assigned to your path variable already.
Change:
list_raster.append(files)
to:
list_raster.append(os.path.join(path, file))
In the example code you posted you are appending files to your list instead of just the current file, in order to get the full path and file name for the current file you would need to change your code to something like this:
import os
list_raster = []
for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
for file in files:
if "woody02.tif" in file:
# path will hold the current directory path where os.walk
# is currently looking and file would be the matching
# woody02.tif
list_raster.append(os.path.join(path, file))
# wait until all files are found before printing the list
print(list_raster)
This question already has answers here:
Rename multiple files in a directory in Python
(15 answers)
Closed 4 years ago.
Looking to change the file extension from .txt to .csv
import os, shutil
for filename in os.listdir(directory):
# if the last four characters are “.txt” (ignoring case)
# (converting to lowercase will include files ending in “.TXT”, etc)
if filename.lower().endswidth(“.txt”):
# generate a new filename using everything before the “.txt”, plus “.csv”
newfilename = filename[:-4] + “.csv”
shutil.move(filename, newfilename)
You can use os and rename.
But let me give you a small advice. When you do these kind of operations as (copy, delete, move or rename) I'd suggest you first print the thing you are trying to achieve. This would normally be the startpath and endpath.
Consider this example below where the action os.rename() is commented out in favor of print():
import os
for f in os.listdir(directory):
if f.endswith('.txt'):
print(f, f[:-4]+'.csv')
#os.rename(f, f[:-4]+'.csv')
By doing this we could be certain things look ok. And if your directory is somewhere else than . You would probably need to do this:
import os
for f in os.listdir(directory):
if f.endswith('.txt'):
fullpath = os.path.join(directory,f)
print(fullpath, fullpath[:-4]+'.csv')
#os.rename(fullpath, fullpath[:-4]+'.csv')
The os.path.join() will make sure the directory path is added too.
This question already has answers here:
How to open every file in a folder
(8 answers)
Closed 2 years ago.
How can I read multiple txt file from a single folder in Python?
I tried with the following code but it is not working.
import glob
import errno
path = '/home/student/Desktop/thesis/ndtvnews/garbage'
files = glob.glob(path)
for name in files:
try:
with open(name) as f:
print name
for line in f:
print line,
f.close()
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
Your glob isn't correct. You should add a /* to the end of your path to select all files (or directories) in your path, and then check if they are files with os.path.isfile. Something like:
from os.path import isfile
files=filter(isfile,glob.glob('%s/*'%path))
You also have an issue with the actual opening. When your with statement ends, the file is closed and f is no longer accessible. Anything you do with the file should be under the with statement. And you shouldn't explicitly close it.
This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 5 years ago.
How to get ONLY filename instead of full path?
For example:
path = /folder/file.txt
and i need to get:
filename = file.txt
How to do that?
You should use the os module:
import os
filename = os.path.basename(path)
For other path manipulations look here (for python 2.7) or here (for python 3)