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.
Related
import os ,fnmatch
import os.path
import os
file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']
for root, dirs,files in os.walk( file_dir ):
for extension in ( tuple(file_type) ):
for filename in fnmatch.filter(files, extension):
filepath = os.path.join(root, filename)
if os.path.isfile( filepath ):
print(filename , 'executing...');
exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())
else:
print('Execution failure!!!')
Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?
Piggybacking off of the original answer since they are close but it isn't a best practice to open and close files that way.
It's better to use a context manager instead of saying f = open() since the context manager will handle closing the resource for you regardless of whether your code succeeds or not.
You use it like,
with open("file.txt","w+") as f:
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
try
Open file
f= open("file.txt","w+")
Insert data into file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Close the file
f.close()
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.
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)
I would like to know if there is any way to activate the webhook for all intents (other than activating it one by one). Thank you!
There is no such functionality as of now, but I had similar problem and this is how I solved it:
Download the zip file of all the intents
Write a program (I wrote in python) to go through all files (ignoring files that ends with usersays
change "webhookUsed": false, to "webhookUsed": true,
Upload the zip file replacing existing intents using Restore from zip option
UPDATE 1:
Below is the code:
import zipfile
import json
import os
import glob
cwd = os.getcwd()
zip_ref = zipfile.ZipFile(cwd + '/filename.zip', 'r')
zip_ref.extractall('zipped')
zip_ref.close()
cwd = cwd + '/zipped/intents'
files = glob.glob(cwd + "/*.json")
for file in files:
print(file)
if "usersay" not in file:
json_data= json.loads(open(file).read())
json_data['webhookUsed'] = True
with open(file, 'w') as outfile:
json.dump(json_data, outfile)
Place the zip file you get from dialogflow in the directory same as where you place above code and run the python program.
After running this code, navigate to directory named zipped and zip all the contents of the file and follow step 4.
UPDATE 2:
Updated the code to make it compatible to multiple languages Dialogflow agent.
Hope it helps.
Aside from activating it one by one, or downloading the zip file, setting it one by tone in the JSON, and uploading the results - no.
#sid8491 thank you so much, this worked for me!
I had to make some changes so that it worked correctly. Your answer has been very helpful. This is my final script:
import zipfile
import json
import os
import glob
cwd = os.getcwd()
zip_ref = zipfile.ZipFile(cwd + '/Bill.zip', 'r')
zip_ref.extractall('zipped')
zip_ref.close()
cwd = cwd + '/zipped/intents'
files = glob.glob(cwd + "/*.json")
for file in files:
print(file)
if "usersay" not in file:
json_data = json.loads(open(file, encoding="utf8").read())
json_data['webhookUsed'] = True
with open(file, 'w') as outfile:
json.dump(json_data, outfile)
else:
print("Usersay file", file)
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()