Hi I cannot open files in python 3 actually I have a problem with the path. I don't know how to write the path for it.:/ For example I have a file(bazi.py) in folder(w8) in driver(F). How should i write it's path. Please help me im an amateur:/
In Windows, there are a couple additional ways of referencing a file. That is because natively, Windows file path employs the backslash "" instead of the slash. Python allows using both in a Windows system, but there are a couple of pitfalls to watch out for. To sum them up:
Python lets you use OS-X/Linux style slashes "/" even in Windows. Therefore, you can refer to the file as 'C:/Users/narae/Desktop/alice.txt'. RECOMMENDED.
If using backslash, because it is a special character in Python, you must remember to escape every instance: 'C:\Users\narae\Desktop\alice.txt'
Alternatively, you can prefix the entire file name string with the rawstring marker "r": r'C:\Users\narae\Desktop\alice.txt'. That way, everything in the string is interpreted as a literal character, and you don't have to escape every backslash.
File Name Shortcuts and CWD (Current Working Directory)
So, using the full directory path and file name always works; you should be using this method. However, you might have seen files called by their name only, e.g., 'alice.txt' in Python. How is it done?
The concept of Current Working Directory (CWD) is crucial here. You can think of it as the folder your Python is operating inside at the moment. So far we have been using the absolute path, which begins from the topmost directory. But if your file reference does not start from the top (e.g., 'alice.txt', 'ling1330/alice.txt'), Python assumes that it starts in the CWD (a "relative path").
using the os.path.abspath function will translate the path to a version appropriate for the operating system.
os.path.abspath(r'F:\w8\bazi.py')
Related
I've been working on a program that reads out an specific PDF and converts the data to an Excel file. The program itself already works, but while trying to refine some aspects I ran into a problem. What happens is the modules I'm working with read directories with simple slashes dividing each folder, such as:
"C:/Users/UserX"
While windows directories are divided by backslashes, such as:
"C:\Users\UserX"
I thought using a simple replace would work just fine:
directory.replace("\" ,"/")
But whenever I try to run the program, the \ isn't identified as a string. Instead it pops up as orange in the IDE I'm working with (PyCharm). Is there anyway to remediate this? Or maybe another useful solution?
In general you should work with the os.path package here.
os.getcwd() gives you the current directory, you can add a subfolder of it via more arguments, and put the filename last.
import os
path_to_file = os.path.join(os.getcwd(), "childFolder", filename)
In Python, the '\' character is represented by '\\':
directory.replace("\\" ,"/")
Just try adding another backslash.
First of all you need to pass "C:\Users\UserX" as a raw string. Use
directory=r"C:\Users\UserX"
Secondly, suppress the backslash using a second backslash.
directory.replace("\\" ,"/")
All of this is required as in python the backslash (\) is a special character known as an escape character.
Try this:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath)
Output:<< C:/temp/myFolder/example/ >>
I have to use a config-file cfg.yml:
---
paths:
reldir : ../my/dir
In Python, I run:
with open('cfg.yml', 'r') as config_file:
cfg = yaml.load(config_file)
and my goal is to do something with some files in the directory reldir, via the Python file. The above works well.
However, this Python program must be able to run on Windows and Linux. If I am not mistaken, they use different path delimiters, / and \\. Thus, I want to make the reldir in the config file more robust:
---
paths:
reldir : os.path.join('..','my','dir').
If my understanding is correct, this will combine these folder names with the correct delimiter, depending on where the Python program is executed.
However, this doesn't work, and print(reldir) outputs os.path.join('..','my','dir') instead of ../my/dir. I.e., it is taking the string literally without evaluating the os.path.join function.
I experimented with exec() and eval(), but first, I could not get it to run anyway; and second, I read here that I shouldn't use these.
How should I best proceed?
Usually "/" works for Windows as well. You can just try "../my/dir"
I am trying to read from a text file but such that I am able to pass the path to the file on the command line.
Like shown below,
path=sys.argv[1]
with open(path,"r") as filestream:
for line in filestream:
currentline=line.split(",")
salt=currentline[0]
X=int(currentline[1])
However, I am getting FilenotFound error when specifying the absolute path. It works when specifying the relative path.
Is there any way to fix this?
For testing, you should print(f'Openining {path}') in order to see what the parameter actually is inside the program.
I suspect you are passing in a path that contains a space. If you are using the path you specify on the command line has spaces in it then you will need to wrap the path in double quotes on Windows or escape the space with a backslash on, say, MacOS.
For example, on a Mac, I'm using python3 test.py /Users/preston/Desktop/untitled\ folder/test.py successfully.
Given this simple code, I receive faulty paths if the userfolder contains any special characters. For example the returned path is expected to be "C:\Users\Aoë\", but the ë is instead shown as a ‰ or a \u2030 depending on what is done with encoding. This then messes up the rest of my code because of attempts to write to nonexistent paths.
I ran into this problem trying to run kivy, but it seems to be happening globally.
from pathlib import Path
home = str(Path.home())
print(home)
I've spent quite some time, but haven't been able to reach a solution. This is with the latest python, x64 on windows with eclipse. No matter what I do, I cannot get python to handle special characters properly.
Try 'r' tag at the beginning, it ignores the special characters:
home = r'%s'%str(Path.home())
I am complete newbie in Python and have to modify existing Python script. The script copies file to other path like following:
err=shutil.copyfile(src, dst)
This works unless dst contains character like &:
dst = "Y:\R&D\myfile.txt"
In this case I get windows error popup that says
Open file or Read file error
Y:\R
I tried to escape & using back slash, double back slash and wrapping the string with additional quotes: dst = "\"Y:\R&D\myfile.txt\"".
Nothing works in last case I get "invalid path" error message from shutil.
How can I solve this problem?
I doubt that ampersand is supported on most platforms. You will likely have to make a call to a windows specific program. I suggest robocopy since its really good at copying files. If it's not included in your version of windows, you can find it in the windows server administrator toolkit for 2003.
It works for me if I change all the \ in the filepaths to / (in both src and dst strings). Yes, I know you're using Windows, but filepaths always seem to be less fussy in Python if you use /, even in Windows.
Also, it looks like you're copying to a network drive. Do you get the same problem copying to c:\R&D\?
What flavor of Windows are you using? shutil.copyfile() works fine for me with & in directory names, in both src and dst paths, in both local and network drives on XP -- as long as I use / in place of \.
Easiest solution, signify to python that the string is raw and not to escape it or modify it in any way:
import shutil
src = r"c:\r&d\file.txt"
dst = r"c:\r&d\file2.txt"
err=shutil.copyfile(src, dst)
Try to escape the "\" with "\ \", this command must work (for example):
shutil.copyfile("Y:\\R&D\\myfile.txt", "C:\\TMP")
Here are few ways to make it work on windows:
Approach 1: (already explained)
import shutil; shutil.copy(src,dest)
as long as src/dest are using r'c:\r&d\file' string format. It also works with forward "/" slashes as well.
Approach 2: Notice use of double quotes instead of single quotes on windows.
src = r'c:\r & d\src_file'
os.system('copy "{}" "{}"'.format(src,dest))
1 file(s) copied
Last resort:
with open(dest, 'wb') as f:
f.write(open(src,'rb').read())
Unlike os.system, this preferred implementation subprocess.call could not work with any quoting approach on windows. I always get The specified path is invalid. Did not try on unix.