Use re module in python re.compile('*ab') [duplicate] - python

This question already has answers here:
Find all files in a directory with extension .txt in Python
(25 answers)
Closed 8 years ago.
I have
os.listdir('/home/dir/')
with file and file.ab
How can I use regex to list only file.ab on that directory.
When i was use regex with
re.compile('*ab')
it return
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib64/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat

Better use glob:
import glob
print glob.glob('/home/dir/*.ab')

no need regex :
[i for i in os.listdir('/home/dir/') if i.endswith(".ab")]

Related

configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%s %s'

I am trying to read from ini file and replace it with os environment variables.
My ini file:
[svc1]
host=%(TEST_IP)s
port=%(TEST_PORT)s
database=test_db
user=test
connect_timeout=3
My python file:
from configparser import ConfigParser
import os
print(os.environ['TEST_IP'])
print(os.environ['TEST_PORT'])
parser = ConfigParser(os.environ)
parser.read('test.ini')
print(parser.items('svc1'))
Output:
192.168.1.1
8080
Traceback (most recent call last):
File "test.py", line 8, in <module>
print(parser.items('svc1'))
File "/usr/lib/python3.8/configparser.py", line 859, in items
return [(option, value_getter(option)) for option in orig_keys]
File "/usr/lib/python3.8/configparser.py", line 859, in <listcomp>
return [(option, value_getter(option)) for option in orig_keys]
File "/usr/lib/python3.8/configparser.py", line 855, in <lambda>
value_getter = lambda option: self._interpolation.before_get(self,
File "/usr/lib/python3.8/configparser.py", line 395, in before_get
self._interpolate_some(parser, option, L, value, section, defaults, 1)
File "/usr/lib/python3.8/configparser.py", line 442, in _interpolate_some
raise InterpolationSyntaxError(
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%s %s'
What am I doing wrong here?
My python version: Python 3.8.10
Python treats the % character differently, when part of the contents of a string can cause this issue.
As per the helpful Python error message (see traceback) rather than escape it, just double it within your original string to %%
A useful way to obfuscate plain text passwords from prying eyes!
FYI configparser.py also does not like the # standard comment character
or empty values so I use = []
As mentioned here:
https://github.com/mobeigi/fb2cal/issues/37
https://github.com/flakshack/pyPerfmon/issues/1

Problem with formated string in OS modul in python [duplicate]

This question already has answers here:
Why can't Python's raw string literals end with a single backslash?
(13 answers)
Closed last year.
I need help with this problem:
temp = "video.mp4"
way_to_file = r"C:\Users\Lukas\Desktop\auto youtube channel\" + temp
the problem is I close the string and can put it together the string and temp I mean It is not working
error:
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
subprocess.call(['hello.py', 'htmlfilename.htm'])
File "C:\Python34\lib\subprocess.py", line 537, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python34\lib\subprocess.py", line 858, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child
startupinfo)
OSError: [WinError 193] %1 is not a valid Win32 application
You can use just
way_to_file = f"C:\\Users\\Lukas\\Desktop\\auto youtube channel\\{temp}"
or
way_to_file = rf"C:\Users\Lukas\Desktop\auto youtube channel\{temp}"
try instead:
temp = "video.mp4"
way_to_file = "C:\\Users\\Lukas\\Desktop\\auto youtube channel\\" + temp

How to fix this file `s' not found error in python?

import patoolib
patoolib.create_archive("file.zip", ("to_pdf.pdf"))
and on running i am getting the error
Traceback (most recent call last):
File "C:\Users\happy\Desktop\Site_Blocker\file_to_archive.py", line 2, in <module>
patoolib.create_archive("file.zip", ("to_pdf.pdf"))
File "C:\Users\happy\AppData\Local\Programs\Python\Python38\lib\site-packages\patoolib\__init__.py", line 712, in create_archive
util.check_archive_filelist(filenames)
File "C:\Users\happy\AppData\Local\Programs\Python\Python38\lib\site-packages\patoolib\util.py", line 422, in check_archive_filelist
check_existing_filename(filename, onlyfiles=False)
File "C:\Users\happy\AppData\Local\Programs\Python\Python38\lib\site-packages\patoolib\util.py", line 398, in check_existing_filename
raise PatoolError("file `%s' was not found" % filename)
patoolib.util.PatoolError: file `t' was not found
Please tell me how to fix this error.
The second argument of create_archive is the filenames. You appear to be trying to give it a tuple, which would work, but the syntax that you have used is not correct for creating a one-element tuple.
("to_pdf.pdf") will evaluate to simply "to_pdf.pdf", and when you iterate over this string you will get the characters in the string, hence the error on the first iteration that there is no file called t.
To create a one-element tuple, you should include the comma:
patoolib.create_archive("file.zip", ("to_pdf.pdf",))
Alternatively, you could use a list:
patoolib.create_archive("file.zip", ["to_pdf.pdf"])

how to upload ziped file on server via ftp [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 3 years ago.
i have this code in python for upload photos.zip file on the server via ftp.
import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('c:\archived\photos.zip','rb') # file to send
session.storbinary('STOR photos.zip', file) # send the file
file.close() # close file and FTP
session.quit()
but i have this error :
T
raceback (most recent call last):
File "a.py", line 24, in <module>
file = open('c:\archived\photos.zip','rb')
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\archived\photos.zip'
You have to escape the backslashes in the path:
file = open('c:\\archived\\photos.zip','rb')
Use os.path.join which is considered better.
file = open(os.path.join('c:/','archived','photos.zip'),'rb')
If you want to stick to your string, use \\ instead of \.

Python Regex Unmatched Groups error with multiple patterns

So I was trying to answer a question on SO when I ran into this issue. Basically a user had the following string:
Adobe.Flash.Player.14.00.125.ie
and wanted to replace it with
Adobe Flash Player 14.00.125 ie
so I used the following re.sub call to solve this issue:
re.sub("([a-zA-Z])\.([a-zA-Z0-9])",r"\1 \2",str)
I then realized that doesn't remove the dot between 125 and ie so I figured I'd try to match another pattern namely:
re.sub("([a-zA-Z])\.([a-zA-Z0-9])|([0-9])\.([a-zA-Z])",r"\1\3 \2\4",str)
When I try to run this, I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/re.py", line 151, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "/usr/lib64/python2.6/re.py", line 278, in filter
return sre_parse.expand_template(template, match)
File "/usr/lib64/python2.6/sre_parse.py", line 793, in expand_template
raise error, "unmatched group"
sre_constants.error: unmatched group
Now, I understand that it's complaining because I'm trying to replace the match with an unmatched group but is there a way around this without having to call re.sub twice?
Without any capturing groups,
>>> import re
>>> s = "Adobe.Flash.Player.14.00.125.ie"
>>> m = re.sub(r'\.(?=[A-Za-z])|(?<!\d)\.', r' ', s)
>>> m
'Adobe Flash Player 14.00.125 ie'

Categories