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

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:
...

Related

How to delete everything in a folder except one or two folders that I want to retain? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have folder "Folder1" that contains files and folders such as "file1", "file2" "Folder11" "Folder12" "Folder13" etc. I want to retain only "Folder11" & "Folder12" and delete rest of the things. I need help to write python script for the same.
You can use the os module to loop through every item and folder in your directory and delete them. You could also define a list with specific items (like your folder names) to prevent them from being deleted. Keep in mind that if you want to keep files from being removed, you also have to add their format (like ".txt" for a text file).
As usual, be careful when deleting files. Maybe you want to add a check before the os.remove() or maybe replace it with a print statement first (print(item)) so that you see what is being removed.
import os # Import the os module
working_directory = r"C:\Users\Vishwesh\Folder1"
retain = ["Folder11", "Folder12", "file1.txt", "file2.txt"]
os.chdir(working_directory) # Change directory to your folder
# Loop through everything in folder in current working directory
for item in os.listdir(os.getcwd()):
if item not in retain: # If it isn't in the list for retaining
os.remove(item) # Remove the item

Python/Powershell/Batch script to move file from one location to another via Parameter for file name? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I would like to implement within my python script, a process to move files from one location to another, based off of parameter that will be inserted to get the file name (ideally a wildcard) .. I am going to implement this into a loop and it file names will change as it loops through, so i will want to be able to pick these files up based off their names.
Any help is appreciated.
Thanks.
Edit:
Now I have taken the suggestion from Trotta (thanks) and have a code sample which I have tried to use. I have made it into a python function with a parameter. The parameter will be constantly changing within the loop, also I do not need to rename the file, just simply move it from one directory to another. However it does not appear to be picking it up. I have created source directory 'release_deployment_scripts' and the target directory 'test_delete' within the root directory of my python project/environment but it's not picking any up. FYI the 2 files I have in the source folder are both 'PostDeploy_BI-Test.sql' and 'PreDeploy_BI_Test.sql' ... do you know what i'm doing wrong? Code below:
import glob
import shutil
def add_deployment_files(Jira):
list_of_files = glob.glob('/release_deployment_scripts/*' + Jira + '*') #source file(s)
for file in list_of_files:
print(file)
new_path = '/test_delete/' # target destination
shutil.move(file, new_path)
add_deployment_files('BI-Test')
One approach to do that in python would be to work with glob and shutil. You could fetch specific files with glob (that allows the use of wildcards) and move them to another path that you define beforehand:
import glob
import shutil
list_of_files = glob.glob('/path/to/directory/B*') # you can work with wildcards here; in this example you would fetch all files in this directory starting with a 'B'
for file in list_of_files:
new_name = '/new/path/filename' # create new name for the file
shutil.move(file, new_name)
As it is not apparent from your question how you would want to implement this into a loop, I assume you'll be able to adapt this snippet to your needs.

python - space in folder 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 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.

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!

Python: How can I open and read files in a directory that do not have a file extension (Windows)? [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 6 years ago.
Improve this question
I am currently in the process of writing a script that will parse a file for a specific string and rename the file to that string. However, the files that this script will be dealing with do not have file extensions. They are readable in any text editor, but they do not have a file type other than the generic "FILE" type in their properties window.
I have tried researching this for a few days now and have been unsuccessful in finding any documentation specific to my problem. So is there any python method of opening, reading, renaming, and saving a file that has no specified file extension?
You can open() or os.rename() all files that you have access to. It doesn't matter if it doesn't have an extension.
If you don't know which files to rename, then just open all files, read their contents and act on the files that match what you're looking for.
import os
# Get a list of all files under the current directory
flist = []
for root, dirs, files in os.walk('.'):
flist += [os.path.join(root, f) for f in files]
# Go over each file and see if it contains the string foo
want = 'foo'
targets = []
for path in flist:
with open(path) as df:
data = df.read()
if want in data:
targets.append(path)
# The targets list now contains the paths of all the files that contain foo.
Have a look at this answer.
When you iterate through the list of files you can simply check if the extension is empty.
def file_has_no_extension(file_path):
"""
Return true if and only if the file has no extension.
"""
filename, file_extension = os.path.splitext('/path/to/somefile.ext')
return not file_extension
For the rest of your question just have a look at tutorials like this.

Categories

Resources