Move first file from folder to current directory - python-3.x

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

Related

How to find and then open file with Python

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())

I am getting FileNotFoundError: [Errno 2] No such file or directory: 'dna.txt' on Pycharm? Where do I put file to read?

I am trying to open 2 text files on PyCharm but it says file not found. Where do I put the files so they can be found?
I tried moving the files to the folder where all my PyCharm projects are kept but it didn't work.
dna = open('dna.txt', 'r')
dna.close()
dna_results = open("dnaresults.txt", "w")
dna_results.close()
Expected: I don't know honestly, for the text file to open on PyCharm so I can read it?
Actual: FileNotFoundError: [Errno 2] No such file or directory: 'dna.txt'
You need to pass the full path of the file in order to open it, for e.g. if the file is located at /home/john/dna.txt, you need to do.
dna = open('/home/john/dna.txt', 'r')
dna.close()
You can put your file anywhere you want, but you always need to pass the full path of the file in order to access it, otherwise the python interpreter doesn't know where to find it.
As an additional tidbit, if the dna.txt is located in the same folder as where the script is located, dna = open('dna.txt', 'r') will work

FileNotFoundError even though file exist

when trying to open a file using wit open .. getting error that file doesn't exist.
I am trying to parse some txt files , when working localy it works with no issue, but the issue started when I am trying to connect to a network folder. the strange this is that is does see the file , but says its not found .
The Path I referring is '//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs/*' (this folder is full of txt files.
but I am still getting this error:
FileNotFoundError: [Errno 2] No such file or directory: 'Console_log_01-01-2019_08-17-56.txt'
as you see , it does see the needed file .
in order to get to this file I am parsing splitting the path the follwoing way :
readFile = name.split("/")[9].split("\\")[1]
because if I am looking on the list of my files I see them the following way :
['//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs\Console_log_01-01-2019_08-17-56.txt',
after splitting I am getting :
Console_log_01-01-2019_08-17-56.txt
and still it says the file is not found.
def main():
lines =0
path = '//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs/*'
files = glob.glob(path)
print ("files")
print ('\n')
print(files)
for name in glob.glob(path):
print (path)
readFile = name.split("/")[9].split("\\")[1]
print(readFile)
with open(readFile,"r") as file:
lines = file.readlines()
print (lines)
main()
files
['//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs\\Console_log_01-01-2019_08-17-56.txt', '//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs\\Console_log_01-01-2019_08-18-29.txt']
Traceback (most recent call last):
//10.8.4.49/Projects/QASA_BR_TCL_Env_7.2.250/Utils/BR_Env/Call Generator/results/Console_Logs/*
Console_log_01-01-2019_08-17-56.txt
File "C:/Users/markp/.PyCharmEdu2018.3/config/scratches/scratch_3.py", line 19, in <module>
main()
File "C:/Users/markp/.PyCharmEdu2018.3/config/scratches/scratch_3.py", line 16, in main
with open(readFile,"r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'Console_log_01-01-2019_08-17-56.txt'
Process finished with exit code 1
When you are looking for the file you are looking in the entire path, however when you are opening the file, you are referencing it as if it was in the local path, either change the current working directory with
os.chdir(path)
before opening the file, or in the open statement use
open(os.path.join(path,filename))
I recommend the first approach if you have to open only one file in your program and second if you open multiple files at multiple directories.
In future better format your questions, stack overflow has multiple tools, use them, also you can see how your text looks, make sure to have a look at it before posting. Use the code brackets for your code, that will help whoever is trying to answer.

Moving all files out from a directory and all its subdirectories

I have a small program that moves all files out of a directory and then searches all subdirectories for other files which it also moves out.
import shutil
import os
import ctypes
import sys
copyfrom = r'D:\Downloads\'
copyto = r'D:\Downloads\'
for r, d, f in os.walk(copyfrom):
for file in f:
if os.path.join(r, file) == copyto:
continue
print(os.path.join(r, file))
shutil.move(os.path.join(r, file), os.path.join(copyto, file))
It works right now but will overwrite every file that has a filename of an existing file. For example if i have banana.mp3 and banana.jpeg it will overwrite one of the files. Instead i would like the file with an existing name to be renamed.
You may check whether the file exists using os.path.exists(destination) . But you should make sure that no race condition is going to happen. So you may open the existing file using a command like os.open(), do your work and then close the file.

Working with shutil and os: [Errno 2] No such file or directory 'folder'

import os, shutil
directory = 'C:\\Users\\MinJun\\Documents\\Python exercise solutions'
def move_files(_dir):
for file in os.listdir(_dir): #check every file in directory
if os.path.isdir(file): #if it is a folder, skip
continue
if file.endswith('.py'): #if file ends with .py, skip
continue
else: #move file to newfolder, (it will automatically create one)
shutil.move(file, directory.join('\\newfolder'))
move_files(directory)
Hello, I am trying to move files that are not folders or .py files to a folder that does not exist (but will be created with shutil.move). I get an error in the shutil module:
FileNotFoundError: [Errno 2] No such file or directory: 'graphics'
My folder 'graphics' is the first item in the directory.
Try
shutil.move(file, ''.join([directory, '\\newfolder'])
join does probably not work as you expected: https://docs.python.org/3.5/library/stdtypes.html#str.join
If you print(directory.join('\\newfolder')) you can see what it resulted in, and that this path for sure does not exist.
There is also os.path.join(path, *paths), which is sort of a "path-aware" string joining function.

Resources