For loop with files with Python - 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.

Related

Python os.chdir() not working with path with spaces and special characters

I'm trying to run some files sequentially (scrape.py, tag.py, save.py and select.py) that are located in a folder named 'cargen'. However, when I try to make os.chdir(path) to access this 'cargen' folder, I'm getting an Exception message because in the path to 'cargen' folder there's a directory with spaces and special characters on it.
The code to run the files sequentially looks like the following:
import os
path = "C:/Users/Desktop/repl/Special Cháracters/cargen/"
os.chdir(path)
directory = 'C:/Users/Desktop/scrap/'
files = ['scrape', 'tag', 'save', 'select']
if __name__ == '__main__':
if not os.path.isdir(directory):
os.mkdir(directory)
[os.system('python ' + path + f'{file}.py ' + directory) for file in files]
The message that I'm getting looks like this:
python: can't open file 'C:/Users/Desktop/repl/\Special': [Errno 2] No such file or directory
I've tried to move to files to a path where there aren't any special characters or spaces in the path and the code works perfectly. Could anybody please help me with this? How should I define the path to 'cargen' to be able to access these files?
NOTE: I'm using Windows 10 with Anaconda
When windows reads comands it uses spaces as separators. e.g.:
my folder -> command1: my, command2: folder
But you can join them adding quotation marks you can join the separated commands in one.
"my folder" -> command1: my folder
I think something similiar is appening to you, try to declare your path like that:
'"your path"'
Finally, the problem wasn't the os.chdir(). The problem was related to os.system() function as #user2357112 mentioned.
The os.system() command was giving me problems due to the spaces in the path. Thus, as the files are all located in the same folder, I have just eliminated that reference to path, resulting in something like:
import os
path = os.getcwd()
os.chdir(path)
directory = 'C:/Users/Desktop/scrap/'
files = ['scrape', 'tag', 'save', 'select']
if __name__ == '__main__':
if not os.path.isdir(directory):
os.mkdir(directory)
[os.system('python ' + f'{file}.py ' + directory) for file in files]

Python Directory Path

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])

Python - how to change directory

I am doing a school assignment where I have to take input from a user and save it to a text file.
My file structure will be something like:
- Customer register
- Customer ID
- .txt files 1-5
It can be saved in the python folder and I can make the folders like this:
os.makedirs("Customer register/Customer ID")
My question is, how do I set the path the text files are to be stored in, in the directory when I don't know the directory? So that no matter where the program is run it is saved in the "Customer ID" folder I create (but on the computer the program is run on)?
Also, how do I make this work on both windows and mac?
I also want to program to be able to be executed several times, and check if the folder is there and save to the "Customer ID" folder if it already exists. Is there a way to do that?
EDIT:
This is the code I am trying to use:
try:
dirs = os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
unique_filename = str(uuid.uuid4())
customerpath = os.getcwd()
os.chdir(customerpath + "/Folder/" + unique_filename)
I am able to create a folder and change the directory (everything in "try" works as I want).
When this folder is created I want to create a second folder with a random generated folder name (used for saving customer files). I can't get this to work in the same way.
Error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\48736\PycharmProjects\tina/Folder/979b9026-b2f6-4526-a17a-3b53384f60c4'
EDIT 2:
try:
os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
os.chdir(os.path.join(path, 'Folder'))
print(os.getcwd())
def userId(folderid):
try:
if not os.path.exists(folderid):
os.makedirs(folderid)
except:
if os.path.exists(folderid):
os.chdir(path + "/Folder/" + folderid)
userId(str(uuid.uuid4()))
print(os.getcwd())
So I can now create a folder, change directory to the folder I have created and create a new folder with a unique filename within that folder.
But I can't change the directory again to the folder with the unique filename.
Any suggestions?
I have tried:
os.chdir(path + "/Folder/" + folderid)
os.chdir(path, 'Folder', folderid)
os.chdir(os.path.join(path, 'Folder', folderid))
But is still just stays in: C:\Users\47896\PycharmProjects\tina\Folder
You can use relative paths in your create directory command, i.e.
os.makedirs("./Customer register/Customer ID")
to create folder in project root (=where the primary caller is located) or
os.makedirs("../Customer register/Customer ID") in parent directory.
You can, of course, traverse the files tree as you need.
For specific options mentioned in your question, please, see makedirs documentation at Python 3 docs
here is solution
import os
import shutil
import uuid
path_on_system = os.getcwd() # directory where you want to save data
path = r'Folder' # your working directory
dir_path = os.path.join(path_on_system, path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_name = str(uuid.uuid4()) # file which you have created
if os.path.exists(file_name) and os.path.exists(dir_path):
shutil.move(file_name,os.path.join(dir_path,file_name))
else:
print(" {} does not exist".format(file_name))

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