Python Directory Path - python

I am trying to write a python script to use the linux command wc to input the amount of lines in a file. I am iterating through a directory inputted by the user. However, whenever I get the absolute path of a file in the directory, it skips the directory it is in. So, the path isn't right and when I call wc on it, it doesn't work because it is trying to find the file in the directory above. I have 2 test text files in a directory called "testdirectory" which is located directly under "projectdirectory".
Script file:
import subprocess
import os
directory = raw_input("Enter directory name: ")
for root,dirs,files in os.walk(os.path.abspath(directory)):
for file in files:
file = os.path.abspath(file)
print(path) #Checking to see the path
subprocess.call(['wc','l',file])
This is what I get when running the program:
joe#joe-VirtualBox:~/Documents/projectdirectory$ python project.py
Enter directory name: testdirectory
/home/joe/Documents/projectdirectory/file2
wc: /home/joe/Documents/projectdirectory/file2: No such file or directory
/home/joe/Documents/projectdirectory/file1
wc: /home/joe/Documents/projectdirectory/file1: No such file or directory
I don't know why the path isn't /home/joe/Documents/projectdirectory/testdirectory/file2 since that is where the file is located.

You're using the output of os.walk wrong.
abspath is related to your program's current working directory, whereas your files are in the directory as specified by root. So you want to use
file = os.path.join(root, file)

Your issue is in the use of os.path.abspath(). All that this function does is appends the current working directory onto whatever the argument to the function is. You also need to have a - before the l option for wc. I think this fix might help you:
import os
directory = input("Enter directory name: ")
full_dir_path = os.path.abspath(directory)
for root,dirs,files in os.walk(full_dir_path):
for file in files:
full_file_path = os.path.join(root, file)
print(full_file_path) #Checking to see the path
subprocess.call(['wc','-l',full_file_path])

Related

For loop with files with Python

I have this code:
import os
directory = "JeuDeDonnees"
for filename in os.listdir(directory):
print("File is: "+filename)
This code run and prints files name in a VSCode/Python environment.
However, when I run it in Sikuli-IDE I got this error:
[error] SyntaxError ( "no viable alternative at input 'for'", )
How can I make this for loop run or is there an alternative that can work?
Answer found ;
Basically, in my Sikuli-IDE environnement, there's layers of Python, Java, Jython... interlocking each other so the Path finding was tedious.
src_file_path = inspect.getfile(lambda: None) #The files we're in
folder = os.path.dirname(src_file_path) # The folder we're in
directory = folder + "\JeuDeDonnees" # Where we wanna go
for filename in os.listdir(directory) # Get the files
print(filename)
We're telling the Path where we are with the current file, get the folder we're in, then moving to "\JeuDeDonnees" and the files.

Opening a file with python in the same directory from different locations

I am currently accessing a script that opens a file in the directory it's located in. I am accessing this file from both the main.py file located in the same directory, as well as a testfile which is located in a "Test" subdirectory. Trying to use a file from the Test subdirectory to call the function that opens the file causes the script to try and open it from the Test directory instead of the super directory, since I am opening the file simply by calling it as following:
with open(filename,"w") as f:
Is there a way to define the location of the file in a way that makes it possible for the script opening it to be called from anywhere?
Use __file__ to get the path to the current script file, then find the file relative to that:
# In main.py: find the file in the same directory as this script
import os.path
open(os.path.join(os.path.dirname(__file__), 'file.txt'))
# In Test/test.py: find the file one directory up from this script
import os.path
open(os.path.join(os.path.dirname(__file__), '..', 'file.txt'))
just give the absolute file path instead of giving a relative one
for eg
abs_path = '/home/user/project/file'
with open(abs_path, 'r') as f:
f.write(data)
Try specifying the path:
import os
path = 'Your path'
path = os.path.abspath(path)
with open(path, 'w') as f:
f.write(data)
From what I understood your file is in a directory parent_directory/file_name.txt
and in another folder parent_directory/sub_directory/file_name.txt. All you have to do is paste the below code in both parent and sub directories.
import os
file_name = 'your_file_name'
# if the file is in current directory set the path to file_name
if file_name in os.listdir(os.getcwd()):
path = file_name
# if the path is not in current directory go back to parent directory set the path to parent directory
else:
path = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
print('from',os.getcwd())
with open(path, 'r') as filename:
print(filename.read())

Recovering filenames from a folder in linux using python

I am trying to use the listdir function from the os module in python to recover a list of filenames from a particular folder.
here's the code:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
list_of_files = os.listdir("/home/admin-pc/Downloads/prank/prank")
print (list_of_files)
I am getting the following error:
OSError: [Errno 2] No such file or directory:
it seems to give no trouble in windows, where you start your directory structure from the c drive.
how do i modify the code to work in linux?
The code is correct. There should be some error with the path you provided.
You could open a terminal and enter into the folder first. In the terminal, just key in pwd, then you could get the correct path.
Hope that works.
You could modify your function to exclude that error with check of existence of file/directory:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
path_to_file = "/home/admin-pc/Downloads/prank/prank"
if os.exists(path_to_file):
list_of_files = os.listdir(path_to_file)
print (list_of_files)

os.chdir() giving error with parsing the path

I am getting error while trying to change the Current directory to a different folder in python. My code is as below:
I take PATH_DIR as input from user and the user passes absolute path.
files[]
for directories in os.listdir(PATH_DIR):
files.append(directories)
for dir in files:
abs = os.path.abspath(dir)
print abs
os.chdir(abs)
In my compilation trail I give the PATH_DIR as C:\Python27\Scripts and the directories in this folder are 'WIN7' 'WIN8'. When I execute the program, I get an error as below.
WindowsError: [Error 2] The system cannot find the file specified: 'C:\Python27\Scripts\WIN7'
In principle, the command os.chdir() is some how adding a '\' character before every '\' in the directory path. Can you please help me solve this issue.
os.chdir(abs)
You are trying to cd into FILE.
os.listdir() will return full content of given directory.
You need to check whether entity is a directory with os.path.isdir()
import os
PATH_DIR = '.'
files = []
for directory in os.listdir(PATH_DIR):
print os.path.isdir(os.path.join('.', directory))
if os.path.isdir(os.path.join('.', directory)):
files.append(directory)
print files
for directory in files:
abs_path = os.path.abspath(directory)
print abs_path
os.chdir(abs_path)

Python: Check if data file exists relative to source code file

I have a small text (XML) file that I want a Python function to load. The location of the text file is always in a fixed relative position to the Python function code.
For example, on my local computer, the files text.xml and mycode.py could reside in:
/a/b/text.xml
/a/c/mycode.py
Later at run time, the files could reside in:
/mnt/x/b/text.xml
/mnt/x/c/mycode.py
How do I ensure I can load in the file? Do I need the absolute path? I see that I can use os.path.isfile, but that presumes I have a path.
you can do a call as follows:
import os
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
This will get you the directory of the python file you're calling from mycode.py
then accessing the xml files is as simple as:
xml_file = "{}/../text.xml".format(BASE_DIR)
fin = open(xml_file, 'r+')
If the parent directory of the two directories are always the same this should work:
import os
path_to_script = os.path.realpath(__file__)
parent_directory = os.path.dirname(path_to_script)
for root, dirs, files in os.walk(parent_directory):
for file in files:
if file == 'text.xml':
path_to_xml = os.path.join(root, file)
You can use the special variable __file__ which gives you the current file name (see http://docs.python.org/2/reference/datamodel.html).
So in your first example, you can reference text.xml this way in mycode.py:
xml_path = os.path.join(__file__, '..', '..', 'text.xml')

Categories

Resources