Why import of regular expressions falling a traceback error? - python-3.x

Having assignment "Extracting Data With Regular Expressions". For this I'm importing regex, but the code is not working. what is my mistake?
I checked the code without "import", it does work. Lines 2-7 are working. But it got a traceback error on "import re" line 1.
import re
fname = input('Enter file: ')
if len(fname) < 1 : fname = "sample.txt"
hand = open(fname)
hd = hand.read()
for line in hand:
line = line.rstrip()
nm = re.findall('[0-9]+',line)
print(nm)
C:\Users\Desktop\new>re.py
Enter file:
Traceback (most recent call last):
File "C:\Users\Desktop\new\re.py", line 1, in <module>
import re
File "C:\Users\Desktop\new\re.py", line 9, in <module>
[enter image description here][1]nm = re.findall('[0-9]+',line)
AttributeError: module 're' has no attribute 'findall'

Because you have called your file re.py, the import will actually import this file instead of the built-in module for regular expressions.
Just rename your file to something different and it should work as expected.

Related

How to randomly copy the contents of a text document to my clipboard

This is my original question
The following script copies the text in /home/my_files/document1.txt to my clipboard.
import pyperclip
path = '/home/my_files/document1.txt'
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Let's say /home/my_files/ contains the following five documents:
/home/my_files/document1.txt
/home/my_files/document2.txt
/home/my_files/document3.txt
/home/my_files/image1.jpg
/home/my_files/image2.png
I would like to create a script to randomly copy the contents of one of the three text documents in /home/my_files/ to my clipboard.
Of course the following script does not work but it shows some of the modules I've been experimenting with.
import glob,random,pyperclip
pattern = "*.txt"
path = random.choice((glob.glob(pattern))("/home/my_files/"))
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Do you have any relevant suggestions for me?
I added the subsequent content to my original question above
When I tried the following solution which #Jacob Lee created...
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())
I received the following error message...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
Someone else suggested the following script to me...
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
But that script doesn't work either. I received the following error when I ran that script...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
I am confused.
The following successfully copies the entire contents of a random text file in /home/my_files/ to my clipboard
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Thanks to #Asocia
Thanks to #Asocia for insisting that the script above works correctly. I don't know what I had been doing wrong, but I must have been doing something wrong when I indicated the script above did not work properly.
You're code raises a TypeError: 'list' object is not callable exception when you try to assign path, in this line:
path = random.choice((glob.glob(pattern))("/home/my_files"))
glob.glob() returns a list (possibly empty). (Also, you put the glob.glob() call inside redundant parentheses.) Then, you try to call glob.glob()("/home/my_files/") (in essence, [...](), raising the TypeError exception.
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files/*.txt")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())

Error when trying to create a file in a path containing parentheses with Python

Can anyone spot why this is failing?
import pathlib
from shlex import quote
path = 'testdir(abc)/subdir(123)'
filename = 'test'
content = \
"""hello
world
"""
pathlib.Path(path).mkdir(mode=0o770, parents=True, exist_ok=True)
md5_filename = quote(str(pathlib.Path(path) / (filename + '.txt')))
with open(md5_filename, 'w') as f:
f.write(content)
I'm getting this traceback
(tools) $ python test_filemake.py
Traceback (most recent call last):
File "test_filemake.py", line 13, in <module>
with open(md5_filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: "'testdir(abc)/subdir(123)/test.txt'"
I think I don't understand posix paths well enough to understand what's going on. If I take the parentheses out of the directory names in the path, it works fine. shlex.quote() is adding the extra layer of double quotes, which seems to be breaking things.

How can I remove Attribute error from my Csv program showing? [duplicate]

So I copied and pasted a demo program from the book I am using to learn Python:
#!/usr/bin/env python
import csv
total = 0
priciest = ('',0,0,0)
r = csv.reader(open('purchases.csv'))
for row in r:
cost = float(row[1]) * float(row[2])
total += cost
if cost == priciest[3]:
priciest = row + [cost]
print("You spent", total)
print("Your priciest purchase was", priciest[1], priciest[0], "at a total cost of", priciest[3])
And I get the Error:
Traceback (most recent call last):
File "purchases.py", line 2, in <module>
import csv
File "/Users/Solomon/Desktop/Python/csv.py", line 5, in <module>
r = csv.read(open('purchases.csv'))
AttributeError: 'module' object has no attribute 'read'
Why is this happening? How do I fix it?
Update:
Fixed All The Errors
Now I'm getting:
Traceback (most recent call last):
File "purchases.py", line 6, in <module>
for row in r:
_csv.Error: line contains NULL byte
What was happening in terms of the CSV.py:
I had a file with the same code named csv.py, saved in the same directory. I thought that the fact that it was named csv .py was screwing it up, so I started a new file called purchases.py, but forgot to delete csv
Don't name your file csv.py.
When you do, Python will look in your file for the csv code instead of the standard library csv module.
Edit: to include the important note in the comment: if there's a csv.pyc file left over in that directory, you'll have to delete that. that is Python bytecode which would be used in place of re-running your csv.py file.
There is a discrepancy between the code in the traceback of your error:
r = csv.read(open('purchases.csv'))
And the code you posted:
r = csv.reader(open('purchases.csv'))
So which are you using?
At any rate, fix that indentation error in line 2:
#!/usr/bin/env python
import csv
total = 0
And create your csv reader object with a context handler, so as not to leave the file handle open:
with open('purchases.csv') as f:
r = csv.reader(f)

undefined unicode in python3

I am trying to follow scrapy docs in scrapy (python3)
using scrapy shell "any_website"
from scrapy.loader.processors import MapCompose, Join
MapCompose(unicode.strip)([u' I',u' am\n'])
I am getting this error `Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
NameError: name 'unicode' is not defined
`
this is affecting my scrapy Item Loader when I use (same error happens)
l = ItemLoader(item=PropertiesItem(), response=response)
l.add_xpath('title', '//*[#itemprop="name"][1]/text()',MapCompose(unicode.strip, unicode.title))
the example on the scrapy docs is pretty straightforward but I am getting this error is it because I use python3 ?
in python2.x:
item = unicode(item, 'utf-8')
in python3.x:
item = str(item.encode('utf-8'))
Python 3 renamed the unicode type to str, the old str type has been replaced by bytes
renaming unicode occurrences with str will worked

Error when Unzipping with Pyside Qtgui

When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.

Resources