Python, Windows. Addressing folder in parent directory - python

I have a "main" folder with two folders inside: "Data" and "Code". "Data" folder contains "limited_scope" folder with .txt files. From "Code" folder I run my_code.py file with lines:
import os
directory_path = '..\\Data\\limited_scope\\'
directorie = sorted(os.listdir(directory_path))
And get the error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: '..\\Data\\limited_scope\\'
When I change to:
directory_path = 'C:\\Users\\myname\\Documents\\main\\Data\\limited_scope\\'
the error disappears.
Can anyone tell the reason of this error?

Your current working directpry while executing the my_code.py should be the Code directory, then this will work.
Otherwise you can try below code which will use my_code.py's folder and use it:
import os
current_dir = os.path.dirname(__file__)
directory_path = os.path.join(current_dir,'..\\Data\\limited_scope\\')
directorie = sorted(os.listdir(directory_path))

Related

Changing the location of text file from one folder to another

I was trying to execute a code in spyder to change a location of text file from one folder to another. But I am repeatedly getting the error that is "File Not Found" even though file exists in the folder. I want to resolve this issue. Can any one help me with it?
import os
from os import path
import shutil
src = "Desktop\This PC\Windows (C:)\new1\test.txt"
dst = "Desktop\This PC\Windows (C:)\new2"
files = [i for i in os.listdir(src) if i.startswith("CTASK") and path.isfile(path.join(src, i))]
for f in files:
shutil.copy(path.join(src, f), dst)

shutil.move() only works with existing folder?

I would like to use the shutil.move() function to move some files which match a certain pattern to a newly created(inside python script)folder, but it seems that this function only works with existing folders.
For example, I have 'a.txt', 'b.txt', 'c.txt' in folder '/test', and I would like to create a folder '/test/b' in my python script using os.join() and move all .txt files to folder '/test/b'
import os
import shutil
import glob
files = glob.glob('./*.txt') #assume that we in '/test'
for f in files:
shutil.move(f, './b') #assume that './b' already exists
#the above code works as expected, but the following not:
import os
import shutil
import glob
new_dir = 'b'
parent_dir = './'
path = os.path.join(parent_dir, new_dir)
files = glob.glob('./*.txt')
for f in files:
shutil.move(f, path)
#After that, I got only 'b' in '/test', and 'cd b' gives:
#[Errno 20] Not a directory: 'b'
Any suggestion is appreciated!
the problem is that when you create the destination path variable name:
path = os.path.join(parent_dir, new_dir)
the path doesn't exist. So shutil.move works, but not like you're expecting, rather like a standard mv command: it moves each file to the parent directory with the name "b", overwriting each older file, leaving only the last one (very dangerous, because risk of data loss)
Create the directory first if it doesn't exist:
path = os.path.join(parent_dir, new_dir)
if not os.path.exists(path):
os.mkdir(path)
now shutil.move will create files when moving to b because b is a directory.

How to use the current folder the program is in?

When I open a file, I have to specify the directory that it is in. Is there a way to specify using the current directory instead of writing out the path name? I'm using:
source = os.listdir("../mydirectory")
But the program will only work if it is placed in a directory called "mydirectory". I want the program to work in the directory it is in, no matter what the name is.
def copyfiles(servername):
source = os.listdir("../mydirectory") # directory where original configs are located
destination = '//' + servername + r'/c$/remotedir/' # destination server directory
for files in source:
if files.endswith("myfile.config"):
try:
os.makedirs(destination, exist_ok=True)
shutil.copy(files,destination)
except:
this is a pathlib version:
from pathlib import Path
HERE = Path(__file__).parent
source = list((HERE / "../mydirectory").iterdir())
if you prefer os.path:
import os.path
HERE = os.path.dirname(__file__)
source = os.listdir(os.path.join(HERE, "../mydirectory"))
note: this will often be different from the current working directory
os.getcwd() # or '.'
__file__ is the filename of your current python file. HERE is now the path of the directory where your python file lives.
'.' stands for the current directory.
try:
os.listdir('./')
or:
os.listdir(os.getcwd())

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)

Categories

Resources