Raw String Python Alternative? - python

I am trying to read in an excel file using xlrd and use tkinter to find the file. I am having trouble with the \ operator. If I would hard code the file path I could use the raw string command, r'filepath'. Is there something similar I could use, like, r(filepath) to convert the string to a raw string? My code and the error is listed below,
import xlrd
from tkinter import Tk, filedialog, messagebox
application_window = Tk()
application_window.withdraw()
messagebox.showinfo("Information", "Select the Layout")
path = filedialog.askopenfilenames(title="Layout")
Layout = xlrd.open_workbook(path)
Error:
File "C:\Program Files\Anaconda3\lib\site-packages\xlrd__init__.py", line 395, in open_workbook with open(filename, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: "('filepath',)"

There is no such thing as a raw-string within a running Python interpreter. raw-strings are only useful for written Python-Code to make it easier for programmers to enter otherwise escaped characters - most notably back-slashes that are also used in regular expressions as escape characters themselves.
Your problem is different: you think you get a path from askopenfilename. But what you get is a tuple with a number of paths, in your case just one.
So just use tkinter.filedialog.askopenfilename without the trailing s to get just one.

Related

How do I read a filepath from a text file using Python?

I am currently trying to write a simple python script that opens a folder or a list of folders using filepaths that I have written down on my text file.
import os
with open('filepaths.txt') as f:
[os.startfile(line) for line in f.readlines()]
My issue is that whenever I run this code, python reads the lines as its non-raw form. The backslashes are doubled, and there is a new line "\n" in every string.
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'D:\\Nitro\\Downloads\n'
I have attempted to solve this problem using repr() on the variable. Instead of removing the backslash, it was doubled even further.
import os
with open('filepaths.txt') as f:
[os.startfile(repr(line)) for line in f.readlines()]
FileNotFoundError: [WinError 2] The system cannot find the file specified: "'D:\\\\Nitro\\\\Downloads\\n'"
I have also attempted to use the string replace function to replace "\" with "". It did not work.
The readlines method reads the file correctly, with the trailing newline character in each line preserved. You just need to strip the newline character from the string before using it as a path name, which is typically done with the str.rstrip method:
for line in f: # no need to use the readlines method for iteration
os.startfile(line.rstrip())
The path name in the error message you included in the question contains double backslashes because it is displayed with the repr function, with backslashes escaped already, not because the path names are read incorrectly.

Python Tkinter save file as CSV creating extra spaces

Normally when I open a CSV file in Python, I need to use:
with open(filename, newline='', mode='w') as f:
And if I don't have that newline='' in there, it creates an empty line between each line in my CSV. However, I am using Tkinter to save the file, so I have:
new_filename = asksaveasfile(mode='w', defaultextension='.csv')
Since "new_filename" is already open, I can't do the "open" command to indicate the newline='' in there. If I try opening it again, I get an error. So how do I get rid of the extra spaces in this case?
Thanks for your help and patience.
you have some other problem regarding the new line parameter - I don't have to use it at all here. But for your tkinter problem, you can use asksaveasfilename instead. That returns the selected file name, then you can open it in any way you want.

Python cannot see csv file

I went through couple answers on forum already but without any success.
I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:
file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'
My code:
import csv
file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.
Completely new to Linux and just can't find why this isn't working.
Each reply appreciated!
You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :
import csv
file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :
import csv
file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)
The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion
Try using the full file path, something like this:
file = open("/home/[username]/Desktop/xyz/city.csv", "rb")
Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.

Cannot open filename that has umlaute in python 2.7 & django 1.9

I am trying doing a thing that goes through every file in a directory, but it crashes every time it meets a file that has an umlaute in the name. Like รค.txt
the shortened code:
import codecs
import os
for filename in os.listdir(WATCH_DIRECTORY):
with codecs.open(filename, 'rb', 'utf-8') as rawdata:
data = rawdata.readline()
# ...
And then I get this:
IOError: [Errno 2] No such file or directory: '\xc3\xa4.txt'
I've tried to encode/decode the filename variable with .encode('utf-8'), .decode('utf-8') and both combined. This usually leads to "ascii cannot decode blah blah"
I also tried unicode(filename) with and without encode/decode.
Soooo, kinda stuck here :)
You are opening a relative directory, you need to make them absolute.
This has nothing really to do with encodings; both Unicode strings and byte strings will work, especially when soured from os.listdir().
However, os.listdir() produces just the base filename, not a path, so add that back in:
for filename in os.listdir(WATCH_DIRECTORY):
fullpath = os.path.join(WATCH_DIRECTORY, filename)
with codecs.open(fullpath, 'rb', 'utf-8') as rawdata:
By the way, I recommend you use the io.open() function rather than codecs.open(). The io module is the new Python 3 I/O framework, and is a lot more robust than the older codecs module.

Python Fileinput openhook=fileinput.hook_compressed syntax use

I'm trying to open a number of files using glob and feed them through a series of functions. Some of my files are gziped some are bz2 and some are plain text. I used fileinput typically but can't figure out the syntax to have it take in compressed files. Based on this Python Fileinput Doc it should be something like:
openhook=fileinput.hook_compressed
My code looks like:
import fileinput
import glob
filestobeanalyzed = glob.glob('./files/*')
for fileName in filestobeanalyzed:
inputfilename = fileName
for line in fileinput.input([inputfilename, openhook=fileinput.hook_compressed]):
#do stuff
I get an invalid syntax on the fileinput line at the = sign.
Any suggestions?
You want
for line in fileinput.input(inputfilename, openhook=fileinput.hook_compressed):
#do stuff
(I removed the square brackets). You were trying to do an assignment in a list constructor. e.g.
my_list=["foo",bar="baz"] #this doesn't work (SyntaxError)
You probably got the idea from the python documentation which uses [ and ] to indicate optional arguments to functions.
This is just an aside -- often there is more information in the traceback which can help pin down the problem than just the type of error and the line number. (read: When you have a traceback, it's generally appreciated if you paste the whole thing so we can see it)

Categories

Resources