how to escape single quote from string - python

This is my problem:
fpaths=os.listdir(ligand_names_list[0].replace("'", "\\'"))
OSError: [Errno 2] No such file or directory: "5-iodoindirubin-3\\'-oxime"
There is a file named 5-iodoindirubin-3'-oxime but I cannot make os.listdir() to find it. Here's another attempt I made inspired by this thread Adding backslashes without escaping [Python] :
fpaths=os.listdir(ligand_names_list[0].__ repr __())
OSError: [Errno 2] No such file or directory: '"5-iodoindirubin-3\'-oxime"'
The problem in this case is the leading single quotes which I don't know how to remove them. Any idea?

You don't have to escape anything; you only have to escape things when entering string literals into your code. Once the string has the right value, you can just use it as it is.
Is the file in the current directory, or in some other directory? (The current directory is the same directory your Python script is in, unless you've changed it.) If it's not in the current directory, that would explain why it's not being found.
(You say it's a file; I hope it is a directory, since you're calling os.listdir() on it...)

Related

Navigating between directories in python

I run the following sequence of commands. The aim was moving between various directories and folders based on the original directory (so it does not need to be apriori coded):
path=os.getcwd()
os.chdir('..')
path2=os.getcwd()
path3=path2+('\\mydir')
os.chdir('path3')
As a result I get an error:
The system cannot find the file specified: 'C:\\work_folder\\mydir'
The directory C:\work_folder\mydir exists in the system, so the problem is in my opinion in missinetrpretation of '\'.
Thus I tried to do the following:
path3=path3.replace(r'\\',r'\')
Again I am getting error:
SyntaxError: EOL while scanning string literal
I will apreciate any help in overcoming this problem. Thank you
In python, instead of using \s in your directories, you can use /s instead and it'll still work.
You can not use a single un-escaped backslash (\) in a raw string. Change the line to:
path3 = path3.replace(r'\\', '\\')
This will solve your second error (SyntaxError: EOL while scanning string literal).

Open an external file in python

x = open('Homework','r')
print(x.name)
x.close()
I got this error when I run the code.
File "C:/Users/LENOVO/Desktop/pythonhome/tobechanged.py", line 16, in <module>
x = open('Homework','r')
FileNotFoundError: [Errno 2] No such file or directory: 'Homework'
SO I tried to type the full path
x = open('C:\Users\LENOVO\Desktop\pythonhome','r')
print(x.name)
x.close()
I got an Unicode error.
btw I'm using windows.
As the comments mentioned, it's usually good to type out the full path to the file, because running a script in IDLE, for example, can cause Python to search for the file in a directory that you are not intending. The reason you got the Unicode error is because you are using a special character, the backslash (\) which starts something known as an escape sequence. Escape sequences allow coders to specify special characters, like the newline character: \n. You can read more about these in Python's docs here
You have to either use a raw string (a string preceded with r, like this r'C:\Users\...'), or escape these characters with double backslashes, like this: C:\\Users\\....
Additionally, you need to specify the extension for the Homework file, otherwise the file system won't be able to find the file you are referring to, resulting in the FileNotFoundError you encountered. As #tdelaney mentioned, these extensions may be hidden by default in Windows Explorer.
Also, the recommended way in Python to open files is using the with statement, as this handles closing the object for you. Here is a sample (assuming that the extension of the Homework file is .txt):
with open('C:\\Users\\LENOVO\\Desktop\\pythonhome\\Homework.txt', 'r') as x:
print(x.name)
It is because you are forgetting the extension to the file (the ending of it). For example, if you have a text file that is named Homework, you would include it in like this
open(r'Homework.txt','r')
For this example, it must be in the same directory as your script. If you wanted to open a file outside of your scripts directory, you would have to find the full path of it. Here is an example of the Homework.txt file in my downloads folder.
open(r'C:\Users\USER\Downloads\Homework.txt','r')
You can also see in this code I use an r infront of the path. This tells Python the expression is a raw string and escape sequences are not parsed.

os.listdir works in console but fails in a script

My script uses os.listdir to get a list of directories to use later for batch analysis.
when running
mypath='//home//user//Documents//data'
datalist=os.listdir(mypath)
in console, I get the correct answer.
However, when I use the same code as a part of the script, python falls over on the datalist line
FileNotFoundError: [Errno 2] No such file or directory: '//home//user//Documents//data//'
Quoted from here:
The r'..' string modifier causes the '..' string to be interpreted
literally. That means, r'My\Path\Without\Escaping' will evaluate to
'My\Path\Without\Escaping' - without causing the backslash to escape
characters. The prior is equivalent to 'My\\Path\\Without\\Escaping'
string, but without the raw modifier.
And there is an explanation with a simple example at this link.
So use
mypath = r'\home\user\Documents\data'

Python FileNotFoundError how to handle long filenames

I have a weird problem. I can neither rename specific files, nor remove them. I get the FileNotFoundError.
Similar questions have been asked before. The solution to this problem was using a full path and not just the filename.
My script worked before using only the filenames, but using different files I get this error, even using the full path.
It seems, that the filename is causing the error, but I cannot resolve it.
import os
cwd = os.getcwd()
file = "003de5664668f009cbaa7944fe188ee1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3."
change = "student_1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3."
oldname = os.path.join(cwd,file)
newname = os.path.join(cwd,change)
print(file in os.listdir())
print(os.path.isfile(file))
os.rename(oldname, newname)
I get the following output:
True
False
Traceback (most recent call last):
File "C:\Users\X\Desktop\code\sub\test.py", line 13, in <module>
os.rename(oldname, newname)
FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden: 'C:\\Users\\X\\Desktop\\code\\sub\\003de5664668f009cbaa7944fe188ee1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3.' -> 'C:\\Users\\X\\Desktop\\code\\sub\\student_1_recursion1.c_2016-04-21-21-06-11_9bacb48fecd32b8cb99238721e7e27a3.'
[Finished in 0.4s with exit code 1]
This file is existing if I use windows search in the folder.
If I try to use the full path I also get an windows error not finding the file.
I have also tried appending a unicode string u''+filename to the strings, because it was suggested by an user.
The pathlength is < 260, so what is causing the problem?
This is a windows/Python thing. Filenames with a trailing period are sometimes trimmed.
If this is a once-off task, you can use two trailing periods as a workaround.
This isn't exactly an answer (I lack the rep for that) but...
Two thoughts:
A) Are those file names supposed to end with periods?
B) Instead of escaping backslashes, you can use forward slashes here (i.e., C:/.../.../...)

Cannot read in files

I have a small problem with reading in my file. My code:
import csv as csv
import numpy
with open("train_data.csv","rb") as training:
csv_file_object = csv.reader(training)
header = csv_file_object.next()
data = []
for row in csv_file_object:
data.append(row)
data = numpy.array(data)
I get the error no such file "train_data.csv", so I know the problem lies with the location. But whenever I specify the pad like this: open("C:\Desktop...etc) it doesn't work either. What am I doing wrong?
If you give the full file path, your script should work. Since it is not, it must be that you have escape characters in your path. To fix this, use a raw-string to specify the file path:
# Put an 'r' at the start of the string to make it a raw-string.
with open(r"C:\path\to\file\train_data.csv","rb") as training:
Raw strings do not process escape characters.
Also, just a technical fact, not giving the full file path causes Python to look for the file in the directory that the script is launched from. If it is not there, an error is thrown.
When you use open() and Windows you need to deal with the backslashes properly.
Option 1.) Use the raw string, this will be the string prefixed with an r.
open(r'C:\Users\Me\Desktop\train_data.csv')
Option 2.) Escape the backslashes
open('C:\\Users\\Me\\Desktop\\train_data.csv')
Option 3.) Use forward slashes
open('C:/Users/Me/Desktop/train_data.csv')
As for finding the file you are using, if you just do open('train_data.csv') it is looking in the directory you are running the python script from. So, if you are running it from C:\Users\Me\Desktop\, your train_data.csv needs to be on the desktop as well.

Categories