python can't find file it just made - python

My program cannot find the path that it just made, the program is for sorting files in the download folder.
If it finds a new type of file it should make a folder for that file type.
import os
FileList = os.listdir("/sdcard/Download/")
for File in FileList:
#print File
extension = ''.join(os.path.splitext(File)[1])
ext = extension.strip('.')
if os.path.exists("/mnt/external_sd/Download/" + ext):
Data = open("/sdcard/Download/" + File, "r").read()
file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data)
elif os.path.exists("/mnt/external_sd/Download/" + ext) != True:
os.makedirs("/mnt/external_sd/Download/" + ext)
Data = open("/sdcard/Download/" + File, "r").read()
file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data)

You create the directory
"/mnt/external_sd/Download/" + ext
but then you are trying to write to
"/mnt/external_sd/" + ext + "/" + File
You dropped the Download folder in that path. Change the last line to:
file("/mnt/external_sd/Download/" + ext + "/" + File, "w").write(Data)
Incidentally, it would be a bit shorter and clearer to write your last seven lines by taking the shared lines out of the if else statement and using shutil.copy instead of reading in the whole file then writing it out again:
import shutil
if not os.path.exists("/mnt/external_sd/Download/" + ext):
os.makedirs("/mnt/external_sd/Download/" + ext)
shutil.copy("/sdcard/Download/" + File, "/mnt/external_sd/Download/" + ext + "/" + File)
(Using shutil will also generally be faster and use less memory, especially if your files are large).

Related

File has moved to other folder. But I can't rename it in spyder

import os
import shutil
src_folder = r"C:\new1\\"
dst_folder = r"C:\new2\\"
file_name = 'testword.docx'
if os.path.exists(dst_folder + file_name):
data = os.path.splitext(file_name)
only_name = data[0]
extension = data[1]
new_base = only_name + 'Renamed' + extension
new_name = os.path.join(dst_folder, new_base)
shutil.move(src_folder + file_name, new_name)
else:
shutil.move(src_folder + file_name, dst_folder + file_name)
I was trying to write a code to move a file from one folder to another and rename it. The file is moving to another folder, But I can't rename it. I am doing this using python(spyder). Can anyone help me with this.

os.rename deleting files python 3

Python novice, my simple script gets a given directory and renames all files sequentially, however it is deleting the files but the print is showing the files names getting renamed, not sure where its going wrong here.
Also, in what order does it retrieve these files?
import os
path = os.path.abspath("D:\Desktop\gp")
i = 0
for file_name in os.listdir(path):
try:
print (file_name + " - " + str(i))
os.rename(os.path.join(path,file_name), str(i))
except WindowsError:
os.remove(str(i))
os.rename(os.path.join(path,file_name), str(i))
i += 1
print(str(i) + " files.")
Edit
Below is the solution with working code, retrieves all files in a dir by creation date and assigns them a iterated number while retaining file extension.
import os
def sorted_dir(folder):
def getctime(name):
path = os.path.join(folder, name)
return os.path.getctime(path)
return sorted(os.listdir(path), key=getctime)
path = os.path.abspath("D:\Path\Here")
i = 0
for file_name in sorted_dir(path):
_, ext = os.path.splitext(file_name)
print (file_name + " - " + str(i)+ext)
os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))
i += 1
print(str(i-1) + " files.")
The problem is that you're using an absolute path for the source, but a relative path for the destination. So the files aren't getting deleted, they're just getting moved into the current working directory.
To fix it so they get renamed into the same directory they were already in, you can do the same thing on the destination you do on the source:
os.rename(os.path.join(path,file_name), os.path.join(path, str(i)))
From a comment, it sounds like you may want to preserve the extensions on these files. To do that:
_, ext = os.path.splitext(file_name)
os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))

Error writing to folder in python os.makedirs()

I am trying to download a .zip file from ftp site, (works independent of the error), I am creating a folder in a directory with the current date in the name. I want the downloaded zip file to be placed in the newly created folder. my code is below.
import os
import urllib
import datetime
now = datetime.datetime.now()
situs = "ftp://pbcgis:sigcbp#ftp.co.palm-beach.fl.us/CWGIS/SITUS_PUB.zip"
path = os.path.join(r"Y:\JH_Data_Dump\SITUS\PBC_SITUS" + str(now.month) + "_" + str(now.day) + "_" + str(now.year))
path1 = os.path.join(path + "PBC_SITUS" + str(now.month) + "_" + str(now.day) + "_" + str(now.year) +".zip")
print "Creating new directory..."
os.makedirs(path)
print "beginning PBC SITUS Download..."
urllib.urlretrieve(situs, path1)
I get no errors and the file downloads successfully but its not placing the .zip into my newly created folder, its placing it the same directory as the folder but not inside.
You use os.path.join incorrectly. Path segments - directories and filename - are distinct arguments. They are joined using path separator, either \ or /.
path = os.path.join('Y:', "PBC_SITUS123")
path1 = os.path.join(path, "PBC_SITUS123" + ".zip")
will result in Y:\PBC_SITUS123\PBC_SITUS123.zip
I figured out why, I was missing a "\" in the path1 string
it should read:
path1 = os.path.join(path + r"\PBC_SITUS" + str(now.month) + "_" + str(now.day) + "_" + str(now.year) +".zip")

Batch rename files in Python 2.7

I'm trying to rename files in a directory so that it the new name is the original name followed by a space + "17-" + an incrementally increasing number.
The code below is just renaming files from 151, upward. How do I keep the original name, adding the text "17-" and the numbers?
import os
path = 'C:\Users\dcs\Desktop\Test direct'
files = os.listdir(path)
i = 151
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.TIF'))
i = i+1
Simply by writing that concatenation expression. If I understand your details correctly, your new loop body would be
new_name = file + " 17-" + str(i) + ".TIF"
os.rename(os.path.join(path, file),
os.path.join(path, new_name) )
i += 1
This would change file "ABC" into file "ABC 17-151.TIF"; the next would contain "17-152", and so on.
FACEPALM
file is a built-in type. Change the loop index.
for fname in files:
new_name = fname + " 17-" + str(i) + ".TIF"
os.rename(os.path.join(path, fname), new_name)
i += 1
If I understand Prune's suggestion above, which I obviously don't, it would look like:
import os
path = 'C:\Users\dcs\Desktop\Test direct'
files = os.listdir(path)
i = 151
#The part that I want to strip the extensions from
for file in files:
new_name = file[:-3]
#The part that words correctly (thanks Prune)
for fname in files:
new_name = fname + " 17-" + str(i) + ".TIF"
os.rename(os.path.join(path, fname), new_name)
i += 1
However the first part, meant to strip the file of it's extension isn't working.

Python - Mac - renamed file is created at the same level with the folder that was containing it

I am trying to rename a file in a specific path, but it moves the file at the same level with the folder that was containing it before being renamed.
import os
path_to_file = "/Users/Me/file.txt" #NOTE that in my code, file name will be randomly generated
path_before_file, file_name = os.path.split(path_to_file) # I need file_name from here, which is the file name without the rest of the path: "file.txt"
renamed_file = os.path.splitext(file_name)[0] + '_renamed' + os.path.splitext(file_name)[1] #This is how renamed file I want to look "file_renamed.txt"
renamed_file_path = os.path.join(path_to_file, renamed_file) #"/Users/Me/file_renamed.txt"
os.rename(path_to_file, renamed_file_path)
After renaming, "/Users/Me/file.txt" becomes "/Users/file.txt"
renamed_file_path = os.path.join(path_to_file, renamed_file) #"/Users/Me/file_renamed.txt"
Above line has a bug. Above line should be as below
renamed_file_path = os.path.join(path_before_file, renamed_file) #"/Users/Me/file_renamed.txt"
I figured out what was the problem. path_before_file was something like "Users/Me"(without slash at the end). If I do:
renamed_file_path = os.path.join(path_before_file + '/' + renamed_file)
or
renamed_file_path = path_before_file + '/' + renamed_file
it works. But AFAIK, you wouldn't need this when working with os.path.join()
This is the code that works:
import os
path_to_file = "/Users/Me/file.txt"
path_before_file, file_name = os.path.split(path_to_file)
renamed_file = os.path.splitext(file_name)[0] + '_renamed' + os.path.splitext(file_name)[1]
renamed_file_path = path_before_file + '/' + renamed_file
os.rename(path_to_file, renamed_file_path)

Categories

Resources