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.
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 use pydub for a music project, but when trying to play sounds with this chunk of code
from pydub import AudioSegment
from pydub.playback import play
sound = AudioSegment.from_wav("s1.wav")
play(sound)
i get the following error:
RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
C:\Python\Python385\lib\site-packages\pydub\utils.py:184: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "C:/Users/vicen/Desktop/music project/mian.py", line 6, in <module>
play(s1)
File "C:\Python\Python385\lib\site-packages\pydub\playback.py", line 74, in play
_play_with_ffplay(audio_segment)
File "C:\Python\Python385\lib\site-packages\pydub\playback.py", line 18, in _play_with_ffplay
seg.export(f.name, "wav")
File "C:\Python\Python385\lib\site-packages\pydub\audio_segment.py", line 809, in export
out_f, _ = _fd_or_path_or_tempfile(out_f, 'wb+')
File "C:\Python\Python385\lib\site-packages\pydub\utils.py", line 60, in _fd_or_path_or_tempfile
fd = open(fd, mode=mode)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\vicen\\AppData\\Local\\Temp\\tmpvwotqts5.wav'
Does someone understand why it isn't working? I am fairly new to python so i don't.
The python script encountered a Permission Error
It is trying to read 'C:\\Users\\vicen\\AppData\\Local\\Temp\\tmpvwotqts5.wav'
file but doesn't have permission to write in the directory.
Changing permissions on the above mentioned Temp folder should solve the problem.
Or you could run your python script using sudo command. Since you are using windows this should help in this regard.
Easy Fix from here:
pip install simpleaudio
Pydub uses tempfiles extensively .As suggested here you can add TMPDIR environment variable.
the problem is with the tempfile , as mentioned here
so the file playback.py , which is one of the files of this pydub module (you may find it at Python\Python-version-\Lib\site-packages\pydub ) , must be modified.
there are two recommended methods to solve this,
mentioned here
create a custom tempfile like below at playback.py
`
import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name, make_chunks
import random
import os
import tempfile
class CustomNamedTemporaryFile:
"""
This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:
> Whether the name can be used to open the file a second time, while the named temporary file is still open,
> varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
"""
def __init__(self, mode='wb', delete=True, suffix = ''):
self._mode = mode
self._delete = delete
self.suffix = suffix
def __enter__(self):
# Generate a random temporary file name
file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
# Ensure the file is created
open(file_name+self.suffix, "x").close()
# Open the file in the given mode
self._tempFile = open(file_name+self.suffix, self._mode)
return self._tempFile
def __exit__(self, exc_type, exc_val, exc_tb):
self._tempFile.close()
if self._delete:
os.remove(self._tempFile.name)
def _play_with_ffplay(seg):
PLAYER = get_player_name()
# with NamedTemporaryFile("w+b", suffix=".wav") as f:
with CustomNamedTemporaryFile(mode='wb', suffix = ".wav") as f:
seg.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", "-hide_banner", f.name])
'
I'm using this to connect to Azure File Share and upload a file. I would like to chose what extension file will have, but I can't. I got an error shown below. If I remove .txt everything works fine. Is there a way to specify file extension while uploading it?
Error:
Exception: ResourceNotFoundError: The specified parent path does not exist.
Code:
def main(blobin: func.InputStream):
file_client = ShareFileClient.from_connection_string(conn_str="<con_string>",
share_name="data-storage",
file_path="outgoing/file.txt")
f = open('/home/temp.txt', 'w+')
f.write(blobin.read().decode('utf-8'))
f.close()
# Operation on file here
f = open('/home/temp.txt', 'rb')
string_to_upload = f.read()
f.close()
file_client.upload_file(string_to_upload)
I believe the reason you're getting this error is because outgoing folder doesn't exist in your file service share. I took your code and ran it with and without extension and in both situation I got the same error.
Then I created a folder and tried to upload the file and I was able to successfully do so.
Here's the final code I used:
from azure.storage.fileshare import ShareFileClient, ShareDirectoryClient
conn_string = "DefaultEndpointsProtocol=https;AccountName=myaccountname;AccountKey=myaccountkey;EndpointSuffix=core.windows.net"
share_directory_client = ShareDirectoryClient.from_connection_string(conn_str=conn_string,
share_name="data-storage",
directory_path="outgoing")
file_client = ShareFileClient.from_connection_string(conn_str=conn_string,
share_name="data-storage",
file_path="outgoing/file.txt")
# Create folder first.
# This operation will fail if the directory already exists.
print "creating directory..."
share_directory_client.create_directory()
print "directory created successfully..."
# Operation on file here
f = open('D:\\temp\\test.txt', 'rb')
string_to_upload = f.read()
f.close()
#Upload file
print "uploading file..."
file_client.upload_file(string_to_upload)
print "file uploaded successfully..."
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 am new to the python language and I am given a task to convert rtf to pdf using python. I googled and found some code- (not exactly rtf to pdf) but I tried working on it and changed it according to my requirement. But I am not able to solve it.
I have used the below code:
import sys
import os
import comtypes.client
#import win32com.client
rtfFormatPDF = 17
in_file = os.path.abspath(sys.argv[1])
out_file = os.path.abspath(sys.argv[2])
rtf= comtypes.client.CreateObject('Rtf.Application')
rtf.Visible = True
doc = rtf.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=rtfFormatPDF)
doc.Close()
rtf.Quit()
But its throwing the below error
Traceback (most recent call last):
File "C:/Python34/Lib/idlelib/rtf_to_pdf.py", line 12, in <module>
word = comtypes.client.CreateObject('Rtf.Application')
File "C:\Python34\lib\site-packages\comtypes\client\__init__.py", line 227, in CreateObject
clsid = comtypes.GUID.from_progid(progid)
File "C:\Python34\lib\site-packages\comtypes\GUID.py", line 78, in from_progid
_CLSIDFromProgID(str(progid), byref(inst))
File "_ctypes/callproc.c", line 920, in GetResult
OSError: [WinError -2147221005] Invalid class string
Can anyone help me with this?
I would really appreciate if someone can find the better and fast way of doing it. I have around 200,000 files to convert.
Anisha
I used Marks's advice and changed it back to Word.Application and my source pointing to rtf files. Works perfectly! - the process was slow but still faster than the JAVA application which my team was using. I have attached the final code in my question.
Final Code:
Got it done using the code which works with Word application :
import sys
import os,os.path
import comtypes.client
wdFormatPDF = 17
input_dir = 'input directory'
output_dir = 'output directory'
for subdir, dirs, files in os.walk(input_dir):
for file in files:
in_file = os.path.join(subdir, file)
output_file = file.split('.')[0]
out_file = output_dir+output_file+'.pdf'
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
If you have Libre Office in your system, you got the best solution.
import os
os.system('soffice --headless --convert-to pdf filename.rtf')
# os.system('libreoffice --headless -convert-to pdf filename.rtf')
# os.system('libreoffice6.3 --headless -convert-to pdf filename.rtf')
Commands may vary to different versions and platforms. But this would be the best solution ever I had.