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.
Related
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')
after researching this error the solution most suggested is to use absolute path instead of relative (which makes sense and obvious)
however this doesnt work in macos.
and I thought python works on all platforms the same
my code:
#!/usr/bin/python3
import os
directory = input("insert path: ")
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
if os.path.isfile(f):
print(f)
once I run this I get a prompt asking me to insert the directory path. so I drag and drop the directory and the absolute path is inserted.
right after I hit enter. I get the famous error file or directory not found.
any help ?
When I run your code and drag a folder from finder into the (iterm2) terminal window, it inserts a space after the path, probably to be helpful in case you want to pass other arguments to a shell, which would be space separated. Remove the space manually before hitting enter, and it should work.
When the path you drag in has spaces, Finder seems to try to quote these spaces, e.g., foo bar becomes foo\ bar. Again this makes sense for a shell, where spaces can be escaped like this, but your Python program is not a shell, so you'd check for \ and replace it with a plain again:
directory = directory.replace(r"\ ", " ")
And if you want to do that kind of processing, you could also remove the trailing space for better usability:
directory = directory.strip()
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 run a batch file through python; however, it is not recognizing the path. It stops reading the path after the space between 'Practice' and 'Folder'. How can I fix this? I've tried the r and using forward and backward slashes. Any help would be awesome. Thank you!
import os
Practice = r"C:\Users\Username\Desktop\Practice Folder\Practice.bat"
os.system(Practice)
'C:\Users\Username\Desktop\Practice' is not recognized as an internal
or external command, operable program or batch file.
Change working directory to the script directory as you are using some relative redirection paths. Pushd changes current directory to any drive and can map network drives. The && chains commands and only runs the right hand command if the left hand command succeeds. %UserProfile% is a standard environmental variable which is usually better then using a fixed path of C:\Users\Username.
import os
Practice = r'pushd "%UserProfile%\Desktop\Practice Folder" && Practice.bat'
os.system(Practice)
Try using call from subprocess module.
You need to enclose the command only in double quotes.
from subprocess import call
call(r'"C:\Users\Username\Desktop\Practice Folder\Practice.bat"')
(Notice the order of placing quotes...)
This would even work with os.system() provided you take care the order of quotation marks.
from os import system
system(r'"C:\Users\Username\Desktop\Practice Folder\Practice.bat"')
This should help fix your problem.
You probably need to use two types of quotation marks e.g.
import os
Practice = r"'C:\Users\Username\Desktop\Practice Folder\Practice.bat'"
os.system(Practice)
As it is, your string does not contain quotation marks - you need to include quotation marks within your string or else Windows will think that Folder\Practice.bat is an argument to the command rather than a continuation of the file path
Try this
import os
Practice = os.path.abspath(r"C:\Users\Username\Desktop\Practice Folder\Practice.bat")
Edit:
Something like this worked for me
os.system(r'"C:\Users\Username\Desktop\Practice Folder\Practice.bat"')
I have a main file which uses(from the main I do a source) a properties file with variables pointing to paths.
The properties file looks like this:
TMP_PATH=/$COMPANY/someProject/tmp
OUTPUT_PATH=/$COMPANY/someProject/output
SOME_PATH=/$COMPANY/someProject/some path
The problem is SOME_PATH, I must use a path with spaces (I can't change it).
I tried escaping the whitespace, with quotes, but no solution so far.
I edited the paths, the problem with single quotes is I'm using another variable $COMPANY in the path
Use one of these threee variants:
SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path
I see Federico you've found solution by yourself.
The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory,
so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
You can escape the "space" char by putting a \ right before it.
SOME_PATH=/mnt/someProject/some\ path
should work
If the file contains only parameter assignments, you can use the following loop in place of sourcing it:
# Instead of source file.txt
while IFS="=" read name value; do
declare "$name=$value"
done < file.txt
This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt.
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/ is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"