I want to move a file from another directory to the current directory. I have no problem with moving a file from current to another. But the other way around I get this error:
FileNotFoundError: [Errno 2] No such file or directory: "'Test''.mp4"
FileNotFoundError: [WinError 2] Cant find file: "'Test''.mp4" -> ".\'Test''.mp4"
filesMove = os.listdir(os.curdir)
for file in filesMove:
if '.mp4' in file:
shutil.move(file, '/Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips')
time.sleep(5)
twitchClipTitle=os.listdir(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips")
print(twitchClipTitle)
filesClips = os.listdir(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Youtube\Clips")
for file in filesClips:
shutil.move(file, os.curdir) #I get the error here
The purpose of this code is to save all the mp4 files' names in a list. Is there a better way?
Include the directory in the call to move and use front slashes. Python will translate the front slashes based on os.
filesMove = os.listdir(os.curdir)
for file in filesMove:
if '.mp4' in file:
shutil.move(file, '/Users/caspe/OneDrive/Documents/Övrigt/Kodning/Youtube/Clips')
time.sleep(5)
twitchClipTitle=os.listdir(r"C:/Users/caspe/OneDrive/Documents/Övrigt/Kodning/Youtube/Clips")
print(twitchClipTitle)
fldr = r"C:/Users/caspe/OneDrive/Documents/Övrigt/Kodning/Youtube/Clips/"
filesClips = os.listdir(fldr)
for file in filesClips:
shutil.move(fldr + file, os.curdir) #I get the error here
Related
This is a school program to learn how to use file and directory in Python. So to do my best I create a function to open, set it as a variable and close properly my file.
But I got the error of the title:
FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'
def load_db():
""" load data base properly
And get ready for later use
Return:
-------
cd : (list) list of tuples
"""
file = open('codedata.pkl', 'rb')
codedata = pickle.loads(file)
file.close()
return codedata
From the interpreter, this is the line
file = open('codedata.pkl', 'rb')
Which is the problem, but I don't see where is the source of the problem.
Can anyone help me?
Can you check what is the location of the file?
If your file is located at /Users/abc/Desktop/, then the code to open the file on python would be as shown below
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
You can also check if the file exists at the desired path by doing something like this
import os
filepath = '/Users/abc/Desktop/codedata.pkl'
if os.path.exists(filepath):
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
else:
print("File not present at desired location")
it happens when you run the script without determining it's the current working directory (example in vs code if you go to Explorer Tape )
You do not work from the same directory that your data.pkl in that's why No file exists
You can know the current directory from getcwd() usually it will be the C/User/.
print(os.getcwd())
filepath=""
if os.path.exists(r"D:\research\StleGAN\karras2019stylegan-ffhq-1024x1024.pkl"):
print("yes")
else:
print("no")
The solution is to open a directory that contains the script or to add the full path.
I already have code that works to modify one .edi file (testedifact.edi) in the same directory as my program.
however I need to run my script against a folder containing many of these .edi files so I basically want to use my code to be applied to every single file
here's what I have that works on one file:
segmentsNew = []
global segments
with open( "testedifact.edi" , "r+") as edifactile:
segments = edifactile.readlines()
versionNumber = getVersionNumber(segments)
for segment in segments:
#do stuffs
edifactile.close()
with open ("testedifact.edi" , "w") as edifactfile:
edifactile.writelines(segmentsNew)
edifactfile.close()
but I want to be able to do this for files outside of this directory and also on our network drives..
I've tried iterating through the files in my directory (as a little test) and passing every file to "with open.." like this
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
with open(file, 'r') as edifactfile:
pass
print(edifactfile.closed)
and I keep getting FileNotFoundError: [Errno 2] No such file or directory: 'testedifact - Kopie (10).edi' though it prints the file name.. what am I doing wrong?
could someone help please?
file only contains the file-name, not the path it is stored in. You need to pass this, too.
path = r'C:\Users\name\test_edi_dir/'
directory = os.listdir(path)
for file in directory:
print("printing file names:", file)
with open(path+file, 'r') as edifactile:
pass
That happens because when you call open(file, 'r') it tries to open a file in the current working directory.
Change your code to this:
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
with open('C:\Users\name\test_edi_dir\' + file, 'r') as edifactile:
pass
print(edifactfile.closed)
The next issue is that some files will be actually a directories, and your code may fail with the following error:
traceback (most recent call last):
File "<stdin>", line 3, in <module>
IOError: [Errno 21] Is a directory: '...'
So you want to check if file is actually a file, before opening it:
isFile = os.path.isfile('C:\Users\name\test_edi_dir\' + file)
And finally a complete code is:
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
full_filename = 'C:\Users\name\test_edi_dir\' + file
if os.path.isdir(full_filename):
continue
with open(full_filename, 'r') as edifactile:
pass
print(edifactfile.closed)
Looks like you have to pass the entire image path:
with open('C:\Users\name\test_edi_dir\' + file, 'r') as edifactile:
pass
I have the following code (file path details kept anonymous):
def stu_activities():
downloadsList = os.listdir("***/Downloads")
destination = "."
for file_name in downloadsList:
if file_name.startswith("Stu_"):
shutil.copyfile(file_name,destination)
stu_activities()
When I run it, it gives me this error:
FileNotFoundError: [Errno 2] No such file or directory: 'Stu_activity.pptx'
How is it that it claims the file is not found yet it still found it?
I assume that your real code does not contain "***/Downloads" but a real path.
os.listdir() returns the filename, but not the full path to the filename.
shutil.copyfile() on the other hand needs the full path of the file.
Further the destination of shutil.copyfile() must be a file name and not a directory
def stu_activities():
dir_to_List = "/your/path/Downloads"
downloadsList = os.listdir(dir_to_list)
destination = "."
for file_name in downloadsList:
if file_name.startswith("Stu_"):
shutil.copyfile(
os.path.join(dir_to_list, file_name) ,
os.path.join(destination, file_name))
stu_activities()
I'm having an issue trying to open a file that is definitely saved to my computer ('NYT-bestsellers.txt'), but whenever I try opening it with my code I get the error
FileNotFoundError: [Errno 2] No such file or directory: 'NYT-bestsellers.txt'
I thought about using the method where you use the full path to open the file… but this is part of an assignment that I'll be submitting later this week. If I open the file using a specific path from my laptop, I'm worried that it won't open for the marker. Please advise!
with open('NYT-bestsellers.txt', 'r') as file:
file = file.splitlines()
As Ryan said, every time you open a file by a relative name, you need to make clear for the current work path.
import sys
import os
current_work_directory = os.getcwd() # Return a string representing the current working directory.
print('Current work directory: {}'.format(current_work_directory))
# Make sure it's an absolute path.
abs_work_directory = os.path.abspath(current_work_directory)
print('Current work directory (full path): {}'.format(abs_work_directory))
print()
filename = 'NYT-bestsellers.txt'
# Check whether file exists.
if not os.path.isfile(filename):
# Stop with leaving a note to the user.
print('It seems file "{}" not exists in directory: "{}"'.format(filename, current_work_directory))
sys.exit(1)
# File exists, go on!
with open(filename, 'r') as file:
file = file.splitlines()
If you confirm that the file will be along with your python script file, you can do some preparatory work before opening the file:
script_directory = os.path.split(os.path.abspath(__file__))[0]
print(script_directory)
abs_filename = os.path.join(script_directory, filename)
print(abs_filename)
with open(abs_filename, 'r') as file:
file = file.splitlines()
This current question is building on from this question.
I am trying to create a python script that will loop through all the text files in the specified folder. The text files contain directories to files that will be moved to a different specified folder. When looping through a text file, it takes the file from the file directory on each line of that text file.
The end goal is to have all the files which are referenced in the text file to move into one specified folder (\1855).
import shutil
dst = r"C:/Users/Aydan/Desktop/1855"
with open(r'C:\Users\Aydan\Desktop\RTHPython\Years') as my_folder:
for filename in my_folder:
text_file_name = filename.strip()
with open (text_file_name) as my_file:
for filename in my_file:
file_name = filename.strip()
src = r'C:\Users\Aydan\Desktop' + file_name
shutil.move(src, dst)
One text file (1855.txt) contains:
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0002_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0003_1.txt
and another text file (1856.txt) contains:
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0004_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0005_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0006_1.txt
This is the error I get when I run the above script:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
with open(r'C:\Users\Aydan\Desktop\RTHPython\Years') as my_folder:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Aydan\\Desktop\\RTHPython\\Years'
This script doesn't seem to be moving the files named here to the C:/Users/Aydan/Desktop/1855 destination, even though in the script I'm trying to follow the same logic of iterating through each item in the text file, but applying that logic to a folder instead of inside text file.
Any help to find a solution would be brilliant! If you need any more info about the files just ask.
Thanks!
Aydan.
Since you can't open whole folders with the open method, you can get cycle through every .txt file in that folder like that:
import shutil
import glob
dst = r"C:/Users/Aydan/Desktop/1855"
for filename in glob.glob(r"C:\Users\Aydan\Desktop\RTHPython\Years\*.txt"):
text_file_name = filename.strip()
with open (text_file_name) as my_file:
for filename in my_file:
file_name = filename.strip()
src = r'C:\Users\Aydan\Desktop' + file_name
shutil.move(src, dst)