delete specific number of files with python [duplicate] - python

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)

Related

Renaming file in Python [duplicate]

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 "))

python FileExistsError: [WinError 183] Cannot create a file when that file already exists: [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 1 year ago.
I am using the following code to loop through multiple subdirectories to append files with .dat extension into a csv but that is not the problem here.
After appending the files into a dataframe i'm trying to create directory and save the file into that directory using os.mkdir() but getting the following error though I'm checking if directory already exists:
FileExistsError: [WinError 183] Cannot create a file when that file already exists:
for root,dirs,files in os.walk(r'C:\Users\ngowda\Downloads\DO_driver_logs'):
for f in files:
print(dirs)
if f.startswith('DC_autofis_'):
all_data_autofis = all_data_autofis.append(pd.read_csv(root+'\\'+f,skiprows=1,sep=',',engine='python',skipinitialspace=True))
dir_ = 'DC_autofis_'
if not os.path.isdir(dir_):
path = os.path.join(path_save_files,dir_)
os.mkdir(path)
all_data_autofis.to_csv(path+'\\'+'DC_autofis_03.csv')
am i doing something wrong in the code?
use if not os.path.exists(directory):
for root,dirs,files in os.walk(r'C:\Users\ngowda\Downloads\DO_driver_logs'):
for f in files:
print(dirs)
if f.startswith('DC_autofis_'):
all_data_autofis = all_data_autofis.append(pd.read_csv(root+'\\'+f,skiprows=1,sep=',',engine='python',skipinitialspace=True))
dir_ = 'DC_autofis_'
if not os.path.isdir(dir_):
path = os.path.join(path_save_files,dir_)
if not os.path.exists(path ):
os.mkdir(path)
all_data_autofis.to_csv(path+'\\'+'DC_autofis_03.csv')

Error: file doesn't exist and no such file or directory python [duplicate]

This question already has an answer here:
IOError: [Errno 2] No such file or directory – os.walk
(1 answer)
Closed 2 years ago.
I have files (data1.txt,data2.txt,....) that I want to iterate, so
I did that:
path='mypath' # not the same python project directory
for root, dirs, files in os.walk(path):
for file in files:
print(file)
f = open(file)
despite the files exist,this shows:
data1.txt
FileNotFoundError: [Errno 2] No such file or directory: 'data1.txt'
I have also a function where I want to use these files, this function works fine when I use a single file that is located in the same python project directory.
process_r=pro_r("data1.txt")
however, when I use it in the for loop above, process_r=pro_r(file), it shows this error: file doesn't exist
The problem is os.walk returns the relative path to the given path. So you need to use this path:
path='mypath' # not the same python project directory
for root, dirs, files in os.walk(path):
for file in files:
print(file)
f = open(path + "/" + file) # / or \\ depends on your OS
you need to join root, and file to get the correct path for your files:
path='mypath' # not the same python project directory
for root, dirs, files in os.walk(path):
for file in files:
print(root, file)
f = open(os.path.join(root, file))

Why I am not getting into the path file " the system cannot find the path specified " [duplicate]

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")

Scan directory and rename files in Python [duplicate]

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.

Categories

Resources