This question already has answers here:
Bug in Python Renaming Program.....No such file or Directory (Fnmatch)
(2 answers)
Closed 6 years ago.
I have 7 files in my web directory like this :
I'm trying to scan through all my files in that folder and rename a certain files.
I have
import os
path = '/Users/username/Desktop/web'
for filename in os.listdir(path):
if filename.startswith("test"):
print 'found'
os.rename(filename, filename.replace("test_", " "))
else:
continue
After run it,
python scan_dir.py
I got
found
Traceback (most recent call last):
File "scan_dir.py", line 9, in <module>
os.rename(filename, filename.replace("test_", " "))
OSError: [Errno 2] No such file or directory
Any hints on what I did wrong ?
When you rename you should use the full path:
import os
path = '/Users/name/Desktop/web'
for filename in os.listdir(path):
if filename.startswith("test"):
print 'found'
os.rename(os.path.join(path, filename), os.path.join(path, filename.replace("test_", " ")))
else:
continue
In your current code what you do use try to rename the file test_3.jpg (from your example) in the current directory, which probably don't exists.
BTW, I would concider using the glob function instead.
Related
This question already has answers here:
What exactly is current working directory?
(5 answers)
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 17 days ago.
I have a folder where want to delete the files on it when they reaches 5 files (or if they are older than 5 days). so far I have tried this:
path_file = r'C:\...\new folder'
files = os.listdir(path_file)
for file in files [:5]:
os.remove(file)
This code gives the next error:
os.remove(file)
FileNotFoundError: [WinError 2] The system cannot find the file specified file
Add path to the filename
path= r'C:\...\new folder'
files = os.listdir(path_file)
for file in files [:5]:
os.remove(path + "\\" + file)
This question already has answers here:
Python raising FileNotFoundError for file name returned by os.listdir
(3 answers)
Closed 2 months ago.
I'm trying to rename the files in a folder, but I can't. This is my code:
import os
directory = r"C:\Users\jhonatta-silva\Downloads"
for file in os.listdir(directory):
if file.startswith("PBI"):
os.rename(file, file.strip("0123456789 "))
and I receive an error like this:
[WinError 2] The system cannot find the file specified: 'PBIItemsResults132.csv' -> 'PBIItemsResults132.csv'
You have to add the directory to the names in the os.rename() call.
import os
directory = r"C:\Users\jhonatta-silva\Downloads"
for file in os.listdir(directory):
if file.startswith("PBI"):
os.rename(os.path.join(directory, file), os.path.join(file.strip("0123456789 ")))
Instead of using os.listdir() and then file.startswith(), you can use glob.glob() to just process files beginning with that prefix. It returns full paths when the argument is a full path.
import os, glob
directory = r"C:\Users\jhonatta-silva\Downloads"
for file in glob.glob(os.path.join(directory, "PBI*")):
os.rename(file, file.rstrip("0123456789 "))
This question already has an answer here:
Python: existing file not found (IOError: [Errno 2]) when using os.walk
(1 answer)
Closed 1 year ago.
My goal is to search for specific JSON files in a directory and to read them so that I can export the content of them as an Excel file.
DIRECTORY LISTING: \Linkedin\linkedin_hb_ma\2021-260\1eb95ebb-d87d-XX1-XXX-XXX1cX
Details: (linkedin hb_ma): the folder contains several folders (year - day) // (year - day): contains several folders with (member ID) // (member ID): contains a Json file
My code:
import os
import json
from pprint import pprint
import win32com.client as win32 # pip install pywin32
rootDir = 'C:/Users/Adam/Desktop/Linkedin/linkedin_hb_ma'
for dirName, subdirList, fileList in os.walk(rootDir , topdown=False):
if dirName.endswith("1eb95ebb-d87d-4aac-XX-XX182"):
abs_path = os.path.join(dirName, file)
print('Found directory: %s' % dirName)
#print(fileList)
for file in fileList:
if file.endswith("activities.json"):
#print('\t%s' % file)
json_data = json.loads(open(abs_path).read())
pprint(json_data)
Error: FileNotFoundError: [Errno 2] No such file or directory: 'activities.json'
NB: my python file is in another working directory.
Does anyone have an idea?
Thank you so much
The issue is that os.walk will not return the absolute file paths for the fileList you will need to concatenate the parent directory and the filename like this:
abs_path = os.path.join(dirName, file)
json_data = json.loads(open(abs_path).read())
This question already has answers here:
Find all files in a directory with extension .txt in Python
(25 answers)
Closed 1 year ago.
1.) I am trying to search for a file hello.py, and return the string in python3
The file path is /Users/Joshua/Appdata/Local/Programs/Python/Python38/User_code/Hello.py
but instead the code returns tons of: {print("file not here")}
2.)I can't run hello.py atm, cause idk - (1)im not in right directory (2)idk if its module/or script (3)first time in python and im new to it.
3.) how should i have set up python to cause less headache??? should i have installed it to /Users/Joshua/ >>>> to cause less headache ?? how did you make it easier for you to learn?
PS: first question im asking on stack overflow...Hooray
import os
File = 'hello.py'
for root, dirs, files in os.walk('/Users/Joshua/Appdata/Local/Programs/Python/Python38/'):
if File in files:
print ("File exists")
if File not in files:
print("file not here")
import os
file_name = "hello.py"
cur_dir = 'C:/Users/Joshua/Appdata/Local/Programs/Python/Python38/'
file_list = os.listdir(cur_dir)
if file_name in file_list:
print("File Exists")
else:
print("File not here")
Call print only when you have a match
import os
File = 'forex.py'
for root, dirs, files in os.walk(os.path.normpath('C:/Users/asus/Desktop/')):
if File in files:
print (os.path.join(root, File))
# if File not in files:
# print("file not here")
Try this:
from pathlib import Path
if Path('./Users/Joshua/Appdata/Local/Programs/Python/Python38/').glob('**/hello.py'):
print('File exists')
else:
print('File does not exist')
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 4 years ago.
So I am using a function in python which is being called in Robotframework to copy a file from a source to destination
I have used os.path.join() and os.listdir() and os.path.normpath() to get access to the folder and copy using shutil
But everytime I get this error
WindowsError: [Error 3] The system cannot find the path specified: '\\10.28.108.***\\folder\\folder2\\out/*.*'
My code
from pathlib import Path
import shutil
import os
#filename = Path ("\\10.28.108.***\folder\folder2\out\001890320181228184056-HT.xml")
source = os.listdir("\\10.28.108.***\folder\folder2\out")
destination = "\\10.28.108.***\folder\folder2\"
for files in source :
if files.endswith(".xml"):
shutil.copy(files, destination)
By this you can read your file.
filename = secure_filename(file_name.filename)
file_split = os.path.splitext(filename)
filename = file_split[0] + '__' + str(uuid.uuid4()) + file_split[1]
filepath = os.path.join(dest_dir, filename)
syspath = os.path.join(upload_dir, filepath)
file_name.save(syspath)
first thing here that check if you can access this folder(\10.28.108.\folder\folder2\out) from your file explorer
The other thing is you have to specify two slash if you are accessing remote folder below is example:
source = os.listdir(r"\\10.28.108.xxx\folder\folder2\out")