The system cannot find the file specified in [WinError 2] - python-3.x

As in the title, I am getting this error,
FileNotFoundError: [WinError 2] The system cannot find the file specified:
I am newbie in coding then, I was coding as, was done in a website called udacity, following them I wrote this code,
import os
def rename_files():
files = os.listdir(r"C:\Users\WIN8\Desktop\oop\prank")
#print(files)
saved_path = os.getcwd()
print("current working directory is" + saved_path)
os.chdir(r"C:\Users\WIN8\Desktop\oop\prank")
for file_temp in files:
os.rename(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789')))
os.chdir(saved_path)
rename_files()
now the error i am getting is
Traceback (most recent call last):
File "C:/Users/WIN8/Desktop/Tumin/First_Program/secret message.py", line 13, in <module>
rename_files()
File "C:/Users/WIN8/Desktop/Tumin/First_Program/secret message.py", line 11, in rename_files
file_temp.translate(str.maketrans('', '', '0123456789')))
FileNotFoundError: [WinError 2] The system cannot find the file specified: '16los angeles.jpg' -> 'los angeles.jpg'
Then i was also getting an error while typing file_temp.translate(None, "0123456789")
then it was saying something like, error2, one argument is needed two is declared or something. then i searched for the problem and in a thread found this code
(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789')))
but it didnt worked either.
Thanks for helping.

Try this:
import os
def rename_files():
fileslst = os.listdir(r"/Users/sachin/MACBOOK/prank")
print(fileslst)
saved_path = os.getcwd()
for filename in fileslst:
os.rename(filename, filename.strip("0123456789"))
os.chdir(saved_path)
rename_files()
Pls. note:
1.Replace the 'prank' folder's path (with folder location on your PC)
2.It'd be a good idea to make prank as your current working dir(cwd)
OR put the images in your cwd (this may be the cause of your ^ error)
The above code is working.
It'll first print the original names of the files in the folder.
Then, once the entire code is run, it'll rename the files in the same folder without any output in the console.
You can visit the folder and see that none of the filenames have any digits.
p.s. if you are not sure of what is currently set as your WD
use the following code:
import os
print('Current working directory path:',os.getcwd())

the problem is indent at os.chdir in loops it must be outside the loop
import os
def rename_files():
files = os.listdir(r"C:\Users\WIN8\Desktop\oop\prank")
#print(files)
saved_path = os.getcwd()
print("current working directory is" + saved_path)
os.chdir(r"C:\Users\WIN8\Desktop\oop\prank")
for file_temp in files:
os.rename(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789')))
os.chdir(saved_path)
rename_files()

Related

Save file path without specifying User

Currently, this code works. It creates a text file named SerialNumber that saves in pictures. The problem is I can't seem to work out how to get it to work on any computer. So for example, if I remove \users\Jarvis from the file path it no longer finds its way to pictures. I'm trying to get it to work no matter who is logged in.
import os
Save_Path='C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt'
with open(Save_Path, 'w') as f:
f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt"')))
I've tried to set it as:
\users\Admin
\users%UserProfile%
\users\user
but that returns
FileNotFoundError: [Errno 2] No such file or directory:
import os
from pathlib import Path
Save_Path= 'C:\\Users\\Pictures\\SerialNumber.txt'
path = Path.home() / "Pictures\SerialNumber.txt"
with open(path, 'w') as f:
f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\%UserProfile%\\Pictures\\SerialNumber.txt"')))
With Subprocess and replace I was able to print to python just the serial number
import subprocess
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
print(result.replace("SerialNumber", ""))
Okay after some help, and research, This is the final code. It uses a subprocess that will output to python>CMD. I then used re (lines 7 and 8) to .strip and re.sub removing everything that wasn't actually the serial number. I installed pyperclip to copy
import subprocess
import pyperclip
import re
import os
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
SerialResult = (result.strip("SerialNumber"))
print(re.sub("[^a-zA-Z0-9]+", "", SerialResult))
pyperclip.copy(re.sub("[^a-zA-Z0-9]+", "", SerialResult))

How to copy from zip file to a folder without unzipping it?

How to make this code works?
There is a zip file with folders and .png files in it. Folder ".\icons_by_year" is empty. I need to get every file one by one without unzipping it and copy to the root of the selected folder (so no extra folders made).
class ArrangerOutZip(Arranger):
def __init__(self):
self.base_source_folder = '\\icons.zip'
self.base_output_folder = ".\\icons_by_year"
def proceed(self):
self.create_and_copy()
def create_and_copy(self):
reg_pattern = re.compile('.+\.\w{1,4}$')
f = open(self.base_source_folder, 'rb')
zfile = zipfile.ZipFile(f)
for cont in zfile.namelist():
if reg_pattern.match(cont):
with zfile.open(cont) as file:
shutil.copyfileobj(file, self.base_output_folder)
zfile.close()
f.close()
arranger = ArrangerOutZip()
arranger.proceed()
shutil.copyfileobj uses file objects for source and destination files. To open the destination you need to construct a file path for it. pathlib is a part of the standard python library and is a nice way to handle file paths. And ZipFile.extract does some of the work of creating intermediate output directories for you (plus sets file metadata) and can be used instead of copyfileobj.
One risk of unzipping files is that they can contain absolute or relative paths outside of the target directory you intend (e.g., "../../badvirus.exe"). extract is a bit too lax about that - putting those files in the root of the target directory - so I wrote a little something to reject the whole zip if you are being messed with.
With a few tweeks to make this a testable program,
from pathlib import Path
import re
import zipfile
#import shutil
#class ArrangerOutZip(Arranger):
class ArrangerOutZip:
def __init__(self, base_source_folder, base_output_folder):
self.base_source_folder = Path(base_source_folder).resolve(strict=True)
self.base_output_folder = Path(base_output_folder).resolve()
def proceed(self):
self.create_and_copy()
def create_and_copy(self):
"""Unzip files matching pattern to base_output_folder, raising
ValueError if any resulting paths are outside of that folder.
Output folder created if it does not exist."""
reg_pattern = re.compile('.+\.\w{1,4}$')
with open(self.base_source_folder, 'rb') as f:
with zipfile.ZipFile(f) as zfile:
wanted_files = [cont for cont in zfile.namelist()
if reg_pattern.match(cont)]
rebased_files = self._rebase_paths(wanted_files,
self.base_output_folder)
for cont, rebased in zip(wanted_files, rebased_files):
print(cont, rebased, rebased.parent)
# option 1: use shutil
#rebased.parent.mkdir(parents=True, exist_ok=True)
#with zfile.open(cont) as file, open(rebased, 'wb') as outfile:
# shutil.copyfileobj(file, outfile)
# option 2: zipfile does the work for you
zfile.extract(cont, self.base_output_folder)
#staticmethod
def _rebase_paths(pathlist, target_dir):
"""Rebase relative file paths to target directory, raising
ValueError if any resulting paths are not within target_dir"""
target = Path(target_dir).resolve()
newpaths = []
for path in pathlist:
newpath = target.joinpath(path).resolve()
newpath.relative_to(target) # raises ValueError if not subpath
newpaths.append(newpath)
return newpaths
#arranger = ArrangerOutZip('\\icons.zip', '.\\icons_by_year')
import sys
try:
arranger = ArrangerOutZip(sys.argv[1], sys.argv[2])
arranger.proceed()
except IndexError:
print("usage: test.py zipfile targetdir")
I'd take a look at the zipfile libraries' getinfo() and also ZipFile.Path() for construction since the constructor class can also use paths that way if you intend to do any creation.
Specifically PathObjects. This is able to do is to construct an object with a path in it, and it appears to be based on pathlib. Assuming you don't need to create zipfiles, you can ignore this ZipFile.Path()
However, that's not exactly what I wanted to point out. Rather consider the following:
zipfile.getinfo()
There is a person who I think is getting at this exact situation here:
https://www.programcreek.com/python/example/104991/zipfile.getinfo
This person seems to be getting a path using getinfo(). It's also clear that NOT every zipfile has the info.

Dynamic file name in directory

I am able to write file in directory using python with following code.
How can I pass the dynamic file name in below code. Right now i am passing hard coded name -'abc.xml'. I have a for loop and file name will be different for each loop iteration. How can i open the directory and then write each file with different file name in it?
import os
if not os.path.exists(directory):
os.makedirs(directory)
with open(directory +"\\"+'abc.xml', 'wb') as file:
file.write(a.content)
Try formatting file name:
import os
if not os.path.exists(directory):
os.makedirs(directory)
for i in range(10):
with open(directory + "\\" + f'abc_{i}.xml', 'wb') as file:
file.write(a.content)
the simple way to get the filename as an argument is by using argv
sys.argv[0] - is the script name - python
sys.argv[1] - is the first argument to the scripts
so you can do the following:
with open(directory +"\\"+sys.argv[1] , 'wb') as file:
file.write(a.content)

Find the latest log file from multiple servers

For our daily monitoring we need to access 16 servers of a particular application and find the latest log file on one of those servers (it usually generates on the first 8).
The problem is that this code is giving me the latest file from each server instead of providing the latest log file from the entire group of servers.
Also, since this is an hourly activity, once the file is processed, it gets archived, so many of the servers don't have any log files present in them at a particular time. Due to this, while the below code is getting executed, I get - ValueError: max() arg is an empty sequence response and the code stops at server 3 if server 4 does not have any log files.
I tried adding default = 0 argument to latest_file but it gives me the error message TypeError: expected str, bytes or os.PathLike object, not int
Can you please help me out here? I am using Python 3.8 and PyCharm.
This is what I have so far :
import glob
import os
import re
paths = [r'\\Server1\Logs\*.log',
r'\\Server2\Logs\*.log',
.....
r'\\Server16\Logs\*.log']
for path in paths:
list_of_files = glob.glob(path)
latest_file = max(list_of_files, key=os.path.getctime)
f = open(os.path.join(latest_file), "r")
print(latest_file)
Create the list first and then find the max.
import glob
import os
import re
paths = [r'\\Server1\Logs\*.log',
r'\\Server2\Logs\*.log',
.....
r'\\Server16\Logs\*.log']
list_of_files = []
for path in paths:
list_of_files.extend(glob.glob(path))
if list_of_files:
latest_file = max(list_of_files, key=os.path.getctime)
f = open(os.path.join(latest_file), "r")
print(latest_file)
else:
print("No log files found!")

Windows FileNotFoundError: [Errno 2] No such file or directory

I want to use 'os.path.join' to open a file, the file exists, but I can not open it and get an error "FileNotFoundError".
This is running python3.6, using PyCharm in Windows10.
The error is occur in this function:
def get_encoder(model_name):
with open(os.path.join('models', model_name, 'encoder.json'), 'r') as f:
encoder = json.load(f)
The output is ' FileNotFoundError: [Errno 2] No such file or directory: 'models\ \345M\ \encoder.json'
My file directory is ' ...\models\345M\encoder.json '
The function is defined by ' ...\encode.py '
It appears that the problem comes from not including the right root folder. Since the encoder.py file is inside the src folder and the path is searching for models inside of src.
The code should be:
def get_encoder(model_name):
with open(os.path.join('..\\models', model_name, 'encoder.json'), 'r') as f:
encoder = json.load(f)
Let me know if this works for you.
I used os.path.abspath to print absolutized version of the pathname.It print D:\Anaconda3\envs\....But my project is in I:\, so I use os.chdir() to change my directory and it works.

Resources