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
Related
I am learning Python and related modules. Here are my scripts.
import tarfile
from six.moves import urllib
data_path = "./datasets/housing/"
file = "housing.tgz"
data_path_file = data_path + file
tar_file = tarfile.open(data_path_file)
# tested following script, failed
tar_file = tarfile.open(data_path_file,'r')
# end test
tar_file.extractall(path=data_path_file)
I hope my scripts can unzip the tgz file and write into a new file. I always received following error messages:
raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully
I checked the path and file name. No errors exist. Any correction and further help would be highly appreciated.
I try to use docxtpl library. docxtpl Use example from documentation:
from docxtpl import DocxTemplate
doc = DocxTemplate("my_word_template.docx")
But there is an error Package not found at '%s'" % pkg_file. If I do this
import os.path
if os.path.isfile('my_word_template.docx'):
print ("File exist")
It is print File exist. File in the same directory as script. Also I tried to use absolute path to file, but that didn't help. In a source I found a place which calls this exception link. How can I fix it?
It probably indicates that the file is not a .docx file. Could you, please, check this file using function is_zipfile from module zipfile?
Try using python-docx by installing it with pip install python-docx.
Then, in you file, write something like this :
try:
document = docx.Document('your_doc_name.docx')
except:
document = docx.Document()
document.save('your_doc_name.docx')
print("Previous file was corrupted or didn't exist - new file was created.")
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')
my code is uploading a txt file to my drop box, but the document it self is empty of content. It only reading inside the title of the file 'test_data.txt', the data itself which is in the real file is not there. The file never updates either when running the script a second time, but I suspect this is because the file is not being updated (it's not actually reading the contents of the .txt file). If anyone could help me with this I would appreciate it.
import dropbox
from dropbox.files import WriteMode
overwrite = WriteMode('overwrite', None)
token = 'xxxx'
dbx = dropbox.Dropbox(token)
dbx.users_get_current_account()
dbx.files_upload('test_data.txt', '/test_data.txt', mode = WriteMode('overwrite'))
files_upload should recieve a content to upload. In your current code you are asking to upload string "test_data.txt" as file "/test_data.txt".
with open('test_data.txt', 'rb') as fh:
dbx.files_upload(fh.read(), '/test_data.txt')
Flask-uploads has something called UploadSet which is described as a "single collection of files". I can use this upload set to save my file to a predefined location. I've defined my setup:
app = Flask(__name__)
app.config['UPLOADS_DEFAULT_DEST'] = os.path.realpath('.') + '/uploads'
app.config['UPLOADED_PHOTOS_ALLOW'] = set(['png', 'jpg', 'jpeg'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
# setup flask-uploads
photos = UploadSet('photos')
configure_uploads(app, photos)
#app.route('/doit', method=["POST"])
def doit():
myfile = request.files['file']
photos.save(myfile, 'subfolder_test', 'filename_test')
return ''' blah '''
This should save to ./uploads/photos/subfolder_test/filename_test.png
My test image is: 2.6MB and is a png file. When I upload this file, I get the error:
...
File "/home/btw/flask/app.py", line 57, in doit
photos.save(myfile, 'subfolder_test', 'filename_test')
File "/usr/local/lib/python2.7/dist-packages/flaskext/uploads.py", line 388, in save
raise UploadNotAllowed()
UploadNotAllowed
However it doesn't say exactly what is not allowed. I have also tried removing all constraints, but the app still throws this error. Why?
EDIT:
Okay, so I figured out that it's not actually the constraints that is causing the problem. It is the subfolder and/or the filename that is causing the problem:
# This works
# saves to: ./uploads/photos/filename_test.png
photos.save(myfile)
But I want to save to my custom location ./uploads/photos/<custom_subdir>/<custom_filename>. What is the correct way of doing this?
You need to give your filename_test the extension as well
photos.save(myfile, 'subfolder_test', 'filename_test.png')
The UploadSet checks the extension on the new file name and will throw the exception if the new extension is not allowed.
Since you are not giving the new file an extension, it does not recognize it.
You can add a dot to file's name, then the file's extension will be appended.
photos.save(myfile, 'subfolder_test', 'filename_test' + '.')
save(storage, folder=None, name=None)
Parameters:
storage – The uploaded file to save.
folder – The subfolder within the upload set to save to.
name – The name to save the file as. If it ends with a dot, the file’s extension will be appended to the end.