Unable to copy or move a file using python shutil - python

import shutil
import os
source = os.listdir("report")
destination = "archieved"
for files in source:
if files.endswith(".json"):
shutil.copy(files, destination)
I have the file named, 'a.json' inside the report folder report/a.json; however, the file is not moved/copied to the target folder
Console Error:
*** FileNotFoundError: [Errno 2] No such file or directory: 'a.json'

os.listdir() returns filenames and not paths. You need to construct the paths from the filenames before calling shutil.copy().
import shutil
import os
source_directory_path = "report"
destination_directory_path = "archived"
for source_filename in os.listdir(source_directory_path):
if source_filename.endswith(".json"):
# construct path from filename
source_file_path = os.path.join(source_directory_path, source_filename)
shutil.copy(source_file_path, destination_directory_path)

Related

File identified but cannot be deleted - Python

So I'm trying to make the a program that deletes files which can be launched from the command lines. But when I run it, it fails and returns the following message: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.txt'. Here's the code:
import sys
import os
num = int(sys.argv[1])
files = os.listdir(sys.argv[2])
for file in files[:num]:
print('Deleting '+file+'...')
os.remove(file)
The file is identified but it cannot be deleted.
You need to add the directory path back to the path:
import sys
import os
num = int(sys.argv[1])
files = os.listdir(sys.argv[2])
for file in files[:num]:
print('Deleting '+file+'...')
os.remove(os.path.join(sys.argv[2], file))
os.listdir will only return the basename of the file, whereas you'll need a relative or full path

what is the correct or best way to input a users home path address into a string?

Hello as the title says i am writing a program which copys data from chrome. my current code is
#library imports
import sys
import shutil
import os
import subprocess
#search and find requried files.
os.path.expanduser('~user') #search for user path
#Making directory
newpath = r'F:\Evidence\Chromium'
newpath = r'F:\Evidence\Chrome'
#Copy chrome file
original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
target = r'F:\Evidence\Chrome'
shutil.copyfile(original, target)
i get a error on the line original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
i assume the script cannot read %LOCALAPPDATA%\ and needs the correct user path ?
what code do i need to input the user directory on a windows PC?
for example C:\Users\(Script to find out this part)\AppData\Local\Google\Chrome\User Data\Default
Scripv3.py", line 25, in <module>
shutil.copyfile(original, target)
File "C:\Users\darks\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: '%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default\\History'
Use the pathlib library.
from pathlib import Path
original = Path.home() / "Google/Chrome/User data/Default/History"
target = Path("F:/Evidence/Chrome")
shutil.copyfile(origina, target)
What you want to do is use os.path.expandvars() function on original variable:
os.path.expandvars(r'%LOCALAPPDATA%')
Will return:
C:\Users\USERNAME\AppData\Local
Where USERNAME is the name of the current user.
So, ensure the variables are expanded for this path:
original = os.path.expandvars(original)
before using it in shutil.copy(original, target)

Copy pdfs in a directory to folders with the same name as the PDFs

I want to put the pdfs I have in a directory in to the folders with the same name. Those folders with the same name have already been created and are in the same directory as the pdf files I want to move in to them.
I am relatively new at python and have not gotten very far on the code. Currently when I run the below it only prints the .pdf files but does not print the subfolders within the directory (that is besides the point but I am not sure why I cant see the sub folders in the directory in the below code.)
import os
from shutil import copyfile
path_to_files = "C:\\tmp\\all_files_converted\\"
def copy_documents(file_path):
for f in os.listdir(file_path):
print(f)
copy_documents(path_to_files)
folders in directory C://tmp//all_files_converted//
pdf files with the same name as the folders in the same directory C://tmp//all_files_converted//
You can use pathlib and shutil to perform this:
from pathlib import Path
from shutil import move
path_to_files = Path(r"C:\tmp\all_files_converted")
for pdf_path in path_to_files.glob("*.pdf"):
dir_path = path_to_files / pdf_path.stem
dir_path.mkdir()
move(pdf_path, dir_path / pdf_path.name)
You can use shutil.move(src, dst)
import shutil
shutil.move(src, dst)
import os
from shutil import copyfile
from glob import glob
path_to_files = "pasta"
def copy_documents(path_to_files):
# os.path is a module to work with file paths
# Using the module glob to list all pdf files of a folder
for file_path in glob(os.path.join(path_to_files, "*.pdf")):
# basename will return the filename without the rest of the path ie: "something.pdf"
pdf_file_name = os.path.basename(file_path)
dest_folder = os.path.join(path_to_files, pdf_file_name[:-4])
print(f"Copy {file_path} to {dest_folder}")
copyfile(file_path, os.path.join(dest_folder, pdf_file_name))
copy_documents(path_to_files)
I recommend reading https://docs.python.org/3/library/os.path.html and https://docs.python.org/3/library/glob.html
for more info.

Error while renaming files with os.rename() in Python

import os
for filename in os.listdir("C:/Users/Awesome/Music"):
if filename.endswith("lyrics.mp3"):
os.rename(filename,filename[0 : len(filename)-11]+".mp3")
The code above returns the error
File "c:/python/lyrics-pop.py", line 6, in <module>
os.rename(filename,filename[0 : len(filename)-11]+".mp3")
FileNotFoundError: [WinError 2] The system cannot find the file specified: '2 Chainz - Bigger Than You (feat Drake Quavo) lyrics.mp3' -> '2 Chainz - Bigger Than You (feat Drake Quavo).mp3'
"""
I have made sure that no other program is accessing the .mp3 files and removed the readonly attribute. What could be causing this?
Probably, the issue is that you are passing relative path to os.rename, add dir to file path, like this:
import os
dir = "C:/Users/Awesome/Music"
for filename in os.listdir(dir):
if filename.endswith("lyrics.mp3"):
os.rename(os.path.join(dir,filename),os.path.join(dir,filename[0 : len(filename)-11])+".mp3")
This is because python can not find the file from where this program is running, since full path is not given.
You can do it as follows:
import os
filedir = "C:/Users/Awesome/Music"
for filename in os.listdir(filedir):
if filename.endswith("lyrics.mp3"):
filepath = os.path.join(filedir, filename)
new_file = os.path.join(filedir, filename[0 : len(filename)-11]+".mp3")
os.rename(filepath, new_file)
As suggested in the comments, the problem seems to be the relative path of the files.
You can use glob, which will give you the full path, i.e.:
from glob import glob
from os import rename
for f in glob("C:/Users/Awesome/Music/*lyrics.mp3"):
rename(f, f[0 : len(f)-11]+".mp3")

How to read unicode filename in python?

I saw lot and lot of forums about unicode, utf-8 but unable to do this.
I am using Windows.
Let's have two folder:
E:\old
---- திருக்குறள்.txt
---- many more unicode named files
E:\new
----
Language : Tamil
Assume I want to move file to E:\new. I cannot access unicode filename properly.
What I Tried
import sys
import os
from shutil import copyfile
path = 'E:/old/'
for root, _, files in os.walk(ur''.join(path)):
files = [f for f in files]
copyfile(files[0].encode('utf-8').strip(),'E:/new/') //just for example
Error:
Traceback (most recent call last):
File "new.py", line 8, in <module>
copyfile(files[0].encode('utf-8').strip(),'E:/new/')
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '\xe0\xae\xa4\xe0\xae\xbf\xe0\xae\xb0\xe0\xaf\x81\xe0\xae\x95\xe0\xaf\x8d\xe0\xae\x95\xe0\xaf\x81\xe0\xae\xb1\xe0\xae\xb3\xe0\xaf\x8d.txt'
In Windows use Unicode paths. Since you are using os.walk() you'll need to handle paths correctly to subdirectories, but you could just use shutil.copytree instead. If you don't need subdirectories, use os.listdir.
Here's something that works with os.walk:
import os
import shutil
for path,dirs,files in os.walk(u'old'):
for filename in files:
# build the source path
src = os.path.join(path,filename)
# build the destination path relative to the source path
dst = os.path.join('new',os.path.relpath(src,'old'))
try:
# ensure the destination directories and subdirectories exist.
os.makedirs(os.path.dirname(dst))
except FileExistsError:
pass
shutil.copyfile(src,dst)

Categories

Resources