Getting file path in python 2.7 - python-2.7

I am having a bit of trouble in obtaining a file path so that I can open and execute my data from the specified (text) file. Below is the code I have written so far:
def pickfile():
options={}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files','.*'), ('text files', '.*txt')]
options['initialfile'] = 'sample.txt'
options['initialdir'] = 'C:\Users\profcs\Desktop'
filename=open(tkFileDialog.askopenfilename(**options))
if filename:
print(filename)
return
with open(filename, 'rb') as f:
reader = csv.reader(f)
try:
for row in reader:
print row
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num,e))
but1 = Button(widget1, text='Pick Your File', command=pickfile)
but1.pack(side=BOTTOM, padx=10, pady=1, anchor=SE)
but1.config(relief=RAISED, bd=2)
When I display a filename, I now get the path in this form:
================ RESTART: C:\Users\profcs\Desktop\BD TEST.py ================
<open file u'C:/Users/profcs/Desktop/sample.txt', mode 'r' at 0x01EFF128>
How can I filter this path and only get 'C:/Users/profcs/Desktop/sample.txt' so that I can open my file?
Thanks in advance.

filename.name gives you the path from filename object.
I hope this helps :
filename = open(tkFileDialog.askopenfilename(**options))
print (filename.name)
'C:/Users/profcs/Desktop/sample.txt'
In your case filename is an object which represents an open file.

Related

read instructions from file python

I have this code:
import os
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename, 'r') as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
else:
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
s = s.replace(old_string, new_string)
f.write(s)
path = raw_input("Enter the file's full path: ")
old = raw_input("String to change: ")
new = raw_input("change to: ")
print "********************************"
print "**** WORKING... PLEASE WAIT ****"
print "********************************\n"
for file in os.listdir(path):
filename = os.path.join(path,file)
inplace_change(filename, old, new)
os.system("pause")
As you can see, the code is replacing sub string in a file with another sub string. I want my code to change text as directed in a text file, like "instruction file" what to change.
The text file will be:
"old_string" "new_string"
"old_string" "new_string"
"old_string" "new_ string"
the result will be that all files in directory will change all the old_string to new_string
How can I do it?

Read uploaded file with csv.reader

Task: read uploaded file to check structure. My test upload file has 5 lines with header and about 20-30 columns. Encoding is ISO-8859-1
Sounds simple but it drives me slowly into insanity.
The only working solution at the moment is detour about Models:
file = request.FILES.getlist('job_file', None)[0]
newdoc = models.Jobs(job_file=file)
newdoc.save()
with codecs.open(newdoc.job_file.name, "r", encoding='iso-8859-1') as fp:
file_content = list(csv.reader(fp, delimiter=';', quotechar='"'))
Dirty, crazy and far from acceptable
Non working solutions:
1:
file_content = list(csv.reader(file, delimiter=';', quotechar='"'))
print(file_content)
>>>_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
2:
file_content = list(csv.reader(file.open('r'), delimiter=';', quotechar='"'))
print(file_content)
>>> TypeError: argument 1 must be an iterator
3:
file_content = list(csv.reader(file.read(), delimiter=';', quotechar='"'))
print(file_content)
>>>_csv.Error: iterator should return strings, not int (did you open the file in text mode?)
Some hints:
print(file.read())
>>>b';"";""\r\n' <-- WRONG see file content at the top
print(file.readlines())
>>>[]
Please save me!
There is no need to open file, you can convert your uploaded file to TextIOWrapper. Here is cleaner example
from io import StringIO
file = request.FILES.getlist('job_file', None)[0]
newdoc = models.Jobs.objects.create(job_file=file)
fp = StringIO(file.read(), encoding='iso-8859-1')
file_content = list(csv.reader(fp, delimiter=';', quotechar='"'))
uploaded = request.FILES.getlist('job_file', None)[0]
decoded_file = uploaded_file.read().decode('ISO-8859-1').splitlines()
file_content = list(csv.reader(decoded_file, delimiter=';', quotechar='"'))

Zipping Directory or file(s) in python

I'm trying to zip files present in a directory and give a specific name (destination folder) to it. I want to pass the source and destination folders as input to the program.
But when ever I'm passeing the source file path it's giving me and error. I guess I'll face the same problem with the destination file path.
d:\SARFARAZ\Python>python zip.py
Enter source directry:D:\Sarfaraz\Python\Project_Euler
Traceback (most recent call last):
File "zip.py", line 17, in <module>
SrcPath = input("Enter source directry:")
File "<string>", line 1
D:\Sarfaraz\Python\Project_Euler
^
SyntaxError: invalid syntax
The code I've written is as follow:
import os
import zipfile
def zip(src, dst):
zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname)
zf.write(absname, arcname)
zf.close()
#zip("D:\\Sarfaraz\\Python\\Project_Euler", "C:\\Users\\md_sarfaraz\\Desktop")
SrcPath = input("Enter source directry:")
SrcPath = ("#'"+ str(SrcPath) +"'")
print SrcPath # checking source path
DestPath = input("Enter destination directry:")
DestPath = ("#'"+str(DestPath) +"'")
print DestPath
zip(SrcPath, DestPath)
i have made some changes to your code as follows:
import os
import zipfile
def zip(src, dst):
zf = zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print 'zipping %s as %s' % (os.path.join(dirname, filename),arcname)
zf.write(absname, arcname)
zf.close()
# Changed from input() to raw_input()
SrcPath = raw_input("Enter source directory: ")
print SrcPath # checking source path
# done the same and also added the option of specifying the name of Zipped file.
DestZipFileName = raw_input("Enter destination Zip File Name: ") + ".zip" # i.e. test.zip
DestPathName = raw_input("Enter destination directory: ")
# Here added "\\" to make sure the zipped file will be placed in the specified directory.
# i.e. C:\\Users\\md_sarfaraz\\Desktop\\
# i.e. double \\ to escape the backlash character.
DestPath = DestPathName + "\\" + DestZipFileName
print DestPath # Checking Destination Zip File name & Path
zip(SrcPath, DestPath)
Good Luck!

downloading multiple files with urllib.urlretrieve

I'm trying to download multiple files from a website.
The url resembles this: foo.com/foo-1.pdf.
Since I want those files to be stored in a directory of my choice,
I have written the following code:
import os
from urllib import urlretrieve
ext = ".pdf"
for i in range(1,37):
print "fetching file " + str(i)
url = "http://foo.com/Lec-" + str(i) + ext
myPath = "/dir/"
filename = "Lec-"+str(i)+ext
fullfilename = os.path.join(myPath, filename)
x = urlretrieve(url, fullfilename)
EDIT : Complete error message.
Traceback (most recent call last):
File "scraper.py", line 10, in <module>
x = urlretrieve(url, fullfilename)
File "/usr/lib/python2.7/urllib.py", line 94, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "/usr/lib/python2.7/urllib.py", line 244, in retrieve
tfp = open(filename, 'wb')
IOError: [Errno 2] No such file or directory: /dir/Lec-1.pdf'
I'd be grateful if someone could point out where I have gone wrong.
Thanks in advance!
As for me your code works (Python3.9). So make sure your script has access to the directory you've specified. Also, it looks like you are trying to open a file which does not exist. So make sure you've downloaded the file before opening it:
fullfilename = os.path.abspath("d:/DownloadedFiles/Lec-1.pdf")
print(fullfilename)
if os.path.exists(fullfilename): # open file only if it exists
with open(fullfilename, 'rb') as file:
content = file.read() # read file's content
print(content[:150]) # print only the first 150 characters
The output would be as follows:
C:/Users/Administrator/PycharmProjects/Tests/dtest.py
d:\DownloadedFiles\Lec-1.pdf
b'%PDF-1.6\r%\xe2\xe3\xcf\xd3\r\n2346 0 obj <</Linearized 1/L 1916277/O 2349/E 70472/N 160/T 1869308/H [ 536 3620]>>\rendobj\r \r\nxref\r\n2346 12\r\n0000000016 00000 n\r'
Process finished with exit code 0

AttributeError in my Python code

I am fairly new in python.
I am parsing a big file and I want to check that the different inputs are correct, especially if the ID entered is in the file header.
When I run the following code, I get this error message:
AttributeError: 'str' object has no attribute 'readlines'
filename = str(raw_input('enter filename: '))
try:
with open(filename, 'rU'): pass
except IOError:
print 'The file does not exist'
sys.exit(0)
def findID(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
while True:
ID = (raw_input("Enter ID: ")).upper()
IDheader = ID + ".NA"
with open(filename, 'rU') as f:
first_line = f.readline()
if findID(IDheader)(first_line):
print "you entered ",ID
break
else:
pass
print "ID not in this file."`
for line in filename.readlines():
Line = line.split()
if...
Thank you
filename is a filename, not a file handle. You need to open it:
with open(filename, 'r') as handle:
for line in handle:
line = line.split()