I have project structure is like
Root
|--config
|---settings.cfg
|--utilities
|---ConfigReader.py
ConfigReader.py
import ConfigParser
config = ConfigParser.ConfigParser()
try:
with open('./config/settings.cfg') as f:
config.readfp(f)
except IOError as e:
raise Exception('Error reading settings.cfg file. '+format(str(e)))
When run above ConfigReader.py, I get always;
raise Exception('Error reading settings.cfg file. '+format(str(e)))
Exception: Error reading settings.cfg file. [Errno 2] No such file or directory: './config/settings.cfg'
I changed providing filepath with back slash/front slash and dots.None working to me.
What Im doing wrong here?
read like this, also make sure that the file is in path.
config = configparser.ConfigParser()
config.read('./config/settings.cfg')
Related
I have made a config file named "config.cfg" that's on the same folder of my .py file.
My config file is like this:
[NetAccess]
host=localhost
port=3306
[Credentials]
username=myuser
password=mypass
[Database]
name=mydb
in my .py file I have this code:
import configparser
config = configparser.ConfigParser()
config.read('config.cfg')
__DBMSuser = config.get('Credentials', 'username')
__DBMSpsw = config.get('Credentials', 'password')
When I launch my program, I receive this error:
configparser.NoSectionError: No section: 'Credentials'
Can someone help me?
I've solved it. My code was correct, and the .cfg file was correctly saved in the folder of my program, but because of other parts of my code, my current directory changed to "C:/Windows/Service32". Not reading the file, I had not error until I was trying to read the sections, so I got NoSectionError.
To solve it, I've choice a standard folder (in AppData) where to save my file and read it and then I've used the absolute path.
Your code is working for me. Most likely the issue is reading the config file itself. Config Parser's read method is configured to fail silently if it fails to find or read the file, but the read function returns a read_ok boolean flag. Use it to check if the read was successful:
import configparser
config = configparser.ConfigParser()
filename = 'config.cfg'
read_ok = config.read(filename)
if read_ok:
__DBMSuser = config['Credentials']['username']
__DBMSpsw = config['Credentials']['password']
else:
print(f'Could not read file {filename}')
There is no mistake in your code, cuz it works for me.
I think there is some small error with file:
Make sure your file is in same directory as python file
Have you saved your file? maybe you forgot to press ctrl+s
If even that's not working for you, try another version of Python
I'm trying to open a file in python and print a message when the file doesn't exist. But I'm confused whether to close the file or not when the exception happens.
try:
file = open(sys.argv[1], "r")
file.close() # should I do this?
except OSError:
print(f"{sys.argv[1]} file not found.")
A simpler method of checking if a file exists:
import os
if not os.path.exists(sys.argv[1]):
print(f"{sys.argv[1]} file not found.")
But to answer your question, the ```file.close()`` happens only when the file exists and you successfully open the file. Not when the exception occurs.
Edit:
As pointed out by #ekhumoro, the above has a race condition (when other processes access that file). If no other process accesses that file, then the above code works.
Solution is as #ekhumoro pointed out is to use your original try/except method.
I am trying some operation in the loop
from obspy import read
for file in glob.glob('*.*'):
st=read(file)
But some particular files in the directory can't be read,and it gives some error.
I want to make a log file which lists the filenames(with path) of files which gives me the error using the logging module.
I was trying something like open a text file and writing the filename on that ( somehow sometimes I ended up with an empty file even though there was error),
f=open('log_response.txt','w')
for file in glob.glob('*.*'):
try:
# block raising an exception
st=read(file)
except:
#If there is any error write the filename to the file or pass
f.write('{}\n'.format(os.path.abspath(file)))
pass
else:
print(st)
f.close()
But I would like to use the logging module
How can I do that?
Try this:
import logging
logging.basicConfig(handlers=[logging.FileHandler(filename="log_response.txt",
encoding='utf-8', mode='a+')],
format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
datefmt="%F %A %T",
level=logging.INFO)
for file in glob.glob('*.*'):
try:
st = read(file)
except:
logging.error('{}'.format(os.path.abspath(file)))
pass
Is there a way for Python to close that the file is already open file.
Or at the very least display a popup that file is open or a custom written error message popup for permission error.
As to avoid:
PermissionError: [Errno 13] Permission denied: 'C:\\zf.csv'
I've seen a lot of solutions that open a file then close it through python. But in my case. Lets say I left my csv open and then tried to run the job.
How can I make it so it closes the currently opened csv?
I've tried the below variations but none seem to work as they expect that I have already opened the csv at an earlier point through python. I suspect I'm over complicating this.
f = 'C:\\zf.csv'
file.close()
AttributeError: 'str' object has no attribute 'close'
This gives an error as there is no reference to opening of file but simply strings.
Or even..
theFile = open(f)
file_content = theFile.read()
# do whatever you need to do
theFile.close()
As well as:
fileobj=open('C:\\zf.csv',"wb+")
if not fileobj.closed:
print("file is already opened")
How do I close an already open csv?
The only workaround I can think of would be to add a messagebox, though I can't seem to get it to detect the file.
filename = "C:\\zf.csv"
if not os.access(filename, os.W_OK):
print("Write access not permitted on %s" % filename)
messagebox.showinfo("Title", "Close your CSV")
Try using a with context, which will manage the close (__exit__) operation smoothly at the end of the context:
with open(...) as theFile:
file_content = theFile.read()
You can also try to copy the file to a temporary file, and open/close/remove it at will. It requires that you have read access to the original, though.
In this example I have a file "test.txt" that is write-only (chmod 444) and it throws a "Permission denied" error if I try writing to it directly. I copy it to a temporary file that has "777" rights so that I can do what I want with it:
import tempfile, shutil, os
def create_temporary_copy(path):
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'temp_file_name')
os.chmod(temp_path, 0o777); # give full access to the tempfile so we can copy
shutil.copy2(path, temp_path) # copy the original into the temp one
os.chmod(temp_path, 0o777); # replace permissions from the original file
return temp_path
path = "./test.txt" # original file
copy_path = create_temporary_copy(path) # temp copy
with open(copy_path, "w") as g: # can do what I want with it
g.write("TEST\n")
f = open("C:/Users/amol/Downloads/result.csv", "r")
print(f.readlines()) #just to check file is open
f.close()
# here you can add above print statement to check if file is closed or not. I am using python 3.5
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.ini')
This is how we read a configuration file in Python. But what if the 'test.ini' file doesn't exist? Why doesn't this method throw an exception?
How can I make it throw exception if the file doesn't exist?
You could also explicitly open it as a file.
try:
with open('test.ini') as f:
config.read_file(f)
except IOError:
raise MyError()
EDIT: Updated for python 3.
From the docs:
If none of the named files exist, the ConfigParser instance will
contain an empty dataset.
If you want to raise an error in case any of the files is not found then you can try:
files = ['test1.ini', 'test2.ini']
dataset = config.read(files)
if len(dataset) != len(files):
raise ValueError("Failed to open/find all config files")