python - space in folder name [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have this next bit of code
Path = os.getenv('PATH')
Path = Path.split(';')
for i, p in enumerate(Path):
if len(P) != 0 and p[-1] != "\\":
Path[i] = p + "\\" #this adds '\' to the ending of each line
printing
Path[0] will show
C:\Program Files (x86)\Common Files\Oracle\Java\javapath\
However, When I try to run anything from this folder, I get the error
'C:\Program' is not recognized
How can I make it search in the entire path and not stop at the space?

There are multiple ways to run. How do you run it? If using os.system, you probably want to use " for the path. For example:
os.system("\"C:\\Program Files (x86)\\aaa.exe\"")
Assuming you are running C:\Program Files (x86)\aaa.exe. Be aware of the two \" in the code.

For good practices you never use spaces, for that you can select relative routes only inside the project, however if you really need to use spaces you can use:
file =__import__=("folder path")
this will import file as folder path separated with spaces.

Related

How to check if a path in python is a file? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was working on a script that does something with the files in a given folder. Put some checks in place to assure that the path given (as a string) is a directory path and is absolute.
if not (os.path.isdir(dirpath) and os.path.isabs(dirpath)):
error_message = f"Path given: \"{dirpath}\" :was inappropriate for required uses."
main_logger.error(error_message)
raise Exception(error_message)
But while testing it on a folder, I got some unexpected results. The folder contained some pdfs in it and the function only extracts the "files" in a folder and ignores any subfolders.
file_list: list[str] = [os.path.join(dirpath, file) for file in os.listdir(dirpath) if os.path.isfile(file)]
But it ignored all pdfs and marked them as "not files". So, how can I check if a path is any file and not just a regular file? I can check if it has an extension or not. But I don't have any good method of doing that.
Checked some other ways to do it, for example:-
pathlib.Path(filepath).is_file()
But that didn't work either.
I have now settled for checking if it is not a directory path. But it could be useful to know about any other ways.
So, any way to do it?
Edit: Difference between any file and a regular file:-
Any file: Any file means that a file with any extension(s). Ex:- main.py, test.h etc.
Regular file: I used the term "regular file" as that is how they are described in the official documentation.
A possible definition could be here.
And the pathlib.Path(filepath).is_file() method "didn't work" meant that it produced the exct same result as the os.path.isfile() method.
Also, I don't want to check for a specific extension either. I want it to work for any file.
you could try
file_list = [os.path.join(dirpath, file) for file in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, file))]
You can simply use .endswith() method.
if file.endswith('.py'):
...
enter code here
else:
...

Delete all files in a directory with a similar name? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
so I am currently somewhat new in python, usually, I do programming in Node.js. I wanted to know if there is a way to delete all files that has a specific name in them?
For example, let's say I have the following files in a directory:
PDforeg.txt
PDahvn.txt
AHgme.txt
Ronra.txt
I want to be able to delete all files that includes the word "PD" in them. How do I do this?
import glob
import os
files = glob.glob("PATH_to_directory/*.txt")
for file in files:
if "PD" in file:
os.remove(file)
import subprocess
subprocess.run('rm *PD*.txt', shell=True)
Or you could import os and do os.remove() stuff.
For multi platform you can use the following script:
import glob
import os
folder = '/home/user/Documents/'
text_to_look_for = 'PD'
for f in glob.glob(folder + '*' + text_to_look_for +'*.txt'):
os.remove(f)
import pathlib
path = pathlib.Path('D:/dev/stackoverflow') # This is your folder
[p.unlink() for p in path.glob('*PD*')]
# Another way of writing the above line
for p in path.glob('*PD*'):
p.unlink()
*PD* will be all files that have PD in them somewhere, not just at the start. If you want to remove files with PD only at the start, use PD*.
In bash, just,
[user ~]$rm *.txt
This command will delete all the files with the same .txt extension in the current directory.

how to copy many files inside of a directory to many other directories using shell or python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
i have many files inside a directory1(libX11.so.6, tm.txt, ff.txt..and so on), i need to copy these files of directory1 to many other directories named as directory2,3.......100000. I tried find command but its not working.My sample online code is given below.can anybody suggest some better solutions using shell or python...Thanks in advance.
find . -type f -name "libX11.so.6, tm.txt, ff.txt" -exec cp -rv {} /home/geo/data/directory{2...100000} \;
while doing this it shows errors
The following code will copy all your original_dir files to the destination_dir.
I believe you can do some customized changes to get what you want.
import os
from shutil import copyfile
original_dir = "/path/to/the/original/dir"
original_files = os.listdir(original_dir)
destination_dir = "/path/to/your/destination/dir"
for each in original_files:
current_file = os.path.join(original_dir, each)
# check if it is a file
if not os.path.isdir(current_file):
# print(each + " is being processing")
copyfile(current_file, destination_folder + each)
You could use the python library shutil to achieve this, code to make this work is below:
import shutil
shutil.copy(src, dst)

How can i cat all txt files to terminal using python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to cat txt files from a folder and cat results should be shown in terminal (Obviously). I have tried using listdir() it but it doesn't work. Required some help!
a simple implementation uses glob to generate absolute paths to files with .txt extension, in a loop which reads the file and prints it on standard output:
import glob,sys
for filepath in sorted(glob.glob("path/to/directory/*.txt")):
with open(filepath) as f:
sys.stdout.write(f.read())
using fileinput allows to read all the files, and line by line, probably less memory intensive and shorter:
import glob,sys,fileinput
for f in fileinput.input(sorted(glob.glob("path/to/directory/*.txt"))):
sys.stdout.write(f)
note that sorted is better to ensure that the files are processed in deterministic order (some filesystems don't respect that order)
sys.stdout.write(f) still writes line by line, but as suggested by comments you could improve performance and not use so much memory by using shutil.copyfileobj(f,sys.stdout)
Just use the command in terminal "cat *"
Or if you want to do it in python:
import os
allTextFileContents = os.popen("cat *").read();
print(allTextFileContents);
You can also do other things with the contents since its stored as a variable!

How to convert IDLE python files into a ZIP folder? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment which needs me to convert 4 separate py files into a zip folder. Do you guys know how to do this?
This is the part of the instruction which tells me to compress it
Programs: Name your programs, q1.py, q2.py, q3.py, q4.py and submit all as a zip file(named A1_my_upi.zip) to the assignment drop box before the deadline (No late submission
accepted).
I have read on the internet that I have to import zipfile. Can some one please clairfy?
Let's say that your files are in /users/matthew/documents/school/assignments/a1. Here are a couple of ways in which you can do this:
Python:
import os
from zipfile import Zipfile
dirpath = '/users/matthew/documents/school/assignments/a1'
with open("A1_my_upi.zip", 'w') as outfile:
for fname in os.listdir(dirpath):
if not fname.endswith('.py'):
continue
outfile.write(os.path.join(dirpath, fname))
Now, you have a A1_my_upi.zip that you can submit
If you're on a linux/mac computer, you can do this:
$ cd /users/matthew/documents/school/assignments/a1
$ cd ..
$ zip A1_my_upi.zip a1/*.py
Now, you have a A1_my_upi.zip that you can submit. It exists at /users/matthew/documents/school/assignments/A1_my_upi.zip

Categories

Resources