How to find and then open file with Python - python-3.x

I want to find a file and open it!
Right now I have some problems!
Basically, I don't know how to find the file, I know how to find a file in the same directory but not globally on the computer! Can anyone help me?
Hier is my code
import os
for root, dirs, files in os.walk(".txt"):
for filename in files:
os.startfile(filename)

Reading the fine documentation would be a good place to start.
"Globally on the computer" means / slash.
Start there, or perhaps in your home directory.
import os
for root, dirs, files in os.walk('/'):
for file in files:
if file.endswith('.txt'):
filename = os.path.join(root, file)
os.startfile(filename)

You can try my answer at:
https://stackoverflow.com/questions/2212643/python-recursive-folder-read/55193831#55193831
code:
import glob
import os
root_dir = <root_dir_here>
for filename in glob.iglob(root_dir + '**/**', recursive=True):
if os.path.isfile(filename):
with open(filename,'r') as file:
print(file.read())

Related

Renaming Files in Subdirectories using file path

Scenario: I am trying to Rename all .txt file named "a.txt" in all subfolders of a directory.
Question: I came up with the following code, but it has and issue: My loops don't work as expected, I was hoping to get the directory loop, to use the last part of the path, and use that string to rename the file. Right now, my code will rename the file with the latest directory name. How can this be fixed?
Code:
import os
import fnmatch
directory = "C:/Users/DGMS/Desktop/Test"
for root, subdirectories, files in os.walk(directory):
for subdirectory in subdirectories:
pathtest = os.path.basename(os.path.normpath(os.path.join(root, subdirectory)))
print(pathtest)
for file in files:
if fnmatch.fnmatch(file, 'a.txt'):
os.rename(os.path.join(root, file),(os.path.join(root, pathtest)))
print(os.path.join(root, file))
Here is a better code for what you want. All "a.txt" now becomes "b.txt"
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file == "a.txt"
os.rename(os.path.join(subdir, file),os.path.join(subdir, "b.txt"))

WinError2 keeps popping up with this python 3.7.3 script to delete files in a file tree without having to scroll through them

I am REALLY (2 days) new to all of this. I am trying to delete a bunch of files in a folder in my external HD with a python 3.7.3 script but an error keeps popping up.
Firstly, this code works fine and finds the folders:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
#os.unlink(filename)
print(filename)
But then when I remove the print(filename) the remove the hash, the folders can't be deleted with the following error popping up:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
os.unlink(filename)
os.unlink(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'rootpractice.docx'
The 'rootpractice' doc is clearly recognised but won't be deleted.
Does anyone know how I can solve this? Any help for this total beginner is much appreciated.
os.unlink and similar other methods which require file paths expect either a link relative to current folder in which your script is running (which you can find out with os.getcwd() ), or the full path.
When you are iterating with os.walk, you are only passing the filename and not the full path. Try this:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
full_path = os.path.join(folderName, filename)
print("About to delete the file: {}".format(full_path))
os.unlink(full_path)

Does the following program access a file in a subfolder of a folder?

using
import sys
folder = sys.argv[1]
for i in folder:
for file in i:
if file == "test.txt":
print (file)
would this access a file in the folder of a subfolder? For Example 1 main folder, with 20 subfolders, and each subfolder has 35 files. I want to pass the folder in commandline and access the first subfolder and the second file in it
Neither. This doesn't look at files or folders.
sys.argv[1] is just a string. i is the characters of that string. for file in i shouldn't work because you cannot iterate a character.
Maybe you want to glob or walk a directory instead?
Here's a short example using the os.walk method.
import os
import sys
input_path = sys.argv[1]
filters = ["test.txt"]
print(f"Searching input path '{input_path}' for matches in {filters}...")
for root, dirs, files in os.walk(input_path):
for file in files:
if file in filters:
print("Found a match!")
match_path = os.path.join(root, file)
print(f"The path is: {match_path}")
If the above file was named file_finder.py, and you wanted to search the directory my_folder, you would call python file_finder.py my_folder from the command line. Note that if my_folder is not in the same directory as file_finder.py, then you have to provide the full path.
No, this won't work, because folder will be a string, so you'll be iterating through the characters of the string. You could use the os module (e.g., the os.listdir() method). I don't know what exactly are you passing to the script, but probably it would be easiest by passing an absolute path. Look at some other methods in the module used for path manipulation.

Move first file from folder to current directory

I need to move the first file of a folder to my current directory:
import os
import shutil
shutil.move(os.listdir('path to folder')[-1], os.getcwd())
I get the error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'name of the file I want to move'
Could someone point out what I am doing wrong, please?
Thank you!
Well, when I've had to move files I wrote something like this:
for file in os.listdir(self.dlPth):
newfile = os.path.join(self.destPth, "name-of-new-file")
shutil.move(os.path.join(self.dlPth,file), newfile)
destPth is the destination path and dlPth is the one where my file was downloaded.
Can you give the paths you are using? I mean the exact way you are writing them in your code?
EDIT
dl = os.path.join(os.getenv('USERPROFILE'), 'Downloads')
shutil.move(os.path.join(dl, os.listdir(dl)[0]), (dl+"\\test\\"))
listdir[index] will only return a file name, not a path. That's why it can't find the wanted file

Python 3.5:Not able to remove non alpha -numeric characters from file_name

i have written a python script to rename all the files present in a folder by removing all the numbers from the file name but this doesn't work .
Note :Same code works fine for python2.7
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
#(2) for each file ,rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
Can anyone tell me how to make it work.Is the translate function which is not working properly
The problem is with os.rename() portion of your code.
os.rename() requires you to give it a full path to the file/folder you want to change it to, while you only gave it the file_name and not the full path.
You have to add the full path to the folders/files directory.
so it should look like this:
def rename_files():
# add the folder path
folder_path = "D:\prank\\"
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
# Concat the folder_path with file_name to create the full path.
for file_name in file_list:
full_path = folder_path + file_name
print (full_path) # See the full path here.
os.rename(full_path, full_path.translate(None, "0123456789"))
look up the documentation for os, heres what ive found on rename:
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file.
This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
If you want cross-platform overwriting of the destination, use replace().
New in version 3.3: The src_dir_fd and dst_dir_fd arguments.
heres a link to the documentation, hope this helps, thanks
https://docs.python.org/3/library/os.html
Others have pointed out other issues with your code, but as to your use of translate, in Python 3.x, you need to pass a dictionary mapping ordinals to new values (or None). This code would work:
import string
...
file_name.translate(dict(ord(c), None for c in string.digits))
but this seems easier to understand:
import re
...
re.sub(r'\d', '', file_name)

Resources