2017-07-07 37 views
3

我有一個腳本:Python的意外移動文件與os.rename

  1. 遍歷目錄中的所有文件+子目錄
  2. 創建文件夾的每個特殊的一年中的文件
  3. 列表
  4. 將文件移動到各自的文件夾年
  5. 根據時間戳+唯一編號對它們進行重命名。

當我只運行零件1-3時,它將文件正確地移動到文件夾。

當我運行部分1-4(包括os.rename部分)時,它會在將文件移回父目錄後重命名這些文件。

啓動文件結構:

parent_folder 
     --> file.txt modified 01-21-2012 
     --> file2.txt modified 09-30-2013 
     --> file3.txt modified 06-21-2017 

預期結果:

parent_folder 
--> '2012' 
     --> 2012-01-21-1.txt 
--> '2013' 
     --> 2013-09-30-2.txt 
--> '2017' 
     --> 2017-06-21-3.txt 

實際結果:

parent_folder 
--> '2012' 
--> '2013' 
--> '2017' 
--> '2012-01-21-1.txt' 
--> '2013-09-30-2.txt' 
--> '2017-06-21-4.txt' 

正如你所看到的,它重命名的文件,但搬到他們出了自己文件夾。它爲什麼這樣做?

我的代碼(我插入記錄打印語句):

import os, datetime, sys, shutil 

#PART 1 : Change to the inputted directory 
#=============================== 

# This is the directory I will work on. 
p = 'ENTER_FOLDER_PATH_HERE' 
print('This is the directory that will be organized:') 
print(os.getcwd()) 
if os.path.isdir(p): # check if directory exists 
    print("Step 1: Changing directory") 
    os.chdir(p) 

#PART 2 : Make a folder for each unique year 
#=========================================== 
    fileNames = next(os.walk(os.getcwd()))[2] # list files, excluding subdirectories 
    f = {} 
    filename = [] 
    dates = [] 

    # Loop through each file and grab the unique year. 
    # Store the file (key) and its modified year (value) into dictionary 'f'. 
    for name in fileNames: 
     f[name] = datetime.datetime.fromtimestamp(os.path.getmtime(name)).strftime("%Y") 
     dates = list(set(f.values())) 

    # Create the list of unique folders from the dictionary. 
    print("Step 2: Creating the following folders:\n", dates) 
    print('\n') 
    [os.mkdir(folder) for folder in dates] 


#PART 3: Move all files to their respective folders based on modified year. 
#========================================================================== 
    if sys.platform == 'Windows': 
     print("Step 3: moving files...") 
     [shutil.move(key, os.getcwd() + '\\' + value) for key, value in f.items()] 
    elif sys.platform == 'darwin': 
     print("Step 3: moving files...") 
     [shutil.move(key, os.getcwd() + '//' + value) for key, value in f.items()] 
    else: 
     print("Sorry, this script is not supported in your OS.") 
else: 
    print("Oops, seems like that directory doesn't exist. Please try again.") 


#PART 4: Rename the files 
#========================================================================== 
# Get each file in directory and renames it to its modified date, Y-M-D format 
count=1 
for root, dir, files in os.walk(p): 
    for file in files: 
     if not file.startswith('.'): # ignore hidden files 
      filePath = os.path.join(root,file) 
      ext = os.path.splitext(filePath)[1] 
      print("File number: ", count, file, ext) 
      print('\n') 
      os.rename(filePath, datetime.datetime.fromtimestamp(os.path.getmtime(filePath)).strftime("%Y-%m-%d") + '-' + str(count) + ext) 
     count += 1 
     print(filePath) 

日誌:

This is the directory that will be organized: 
TEST_PATH 
Step 1: Changing directory 
Step 2: Creating the following folders: 
['2013', '2012', '2017'] 


Step 3: moving files... 
File number: 1 2012-01-21-1.jpg TEST_PATH/2012/2012-01-21-1.jpg 
TEST_PATH//2012/2012-01-21-1.jpg 

File number: 2 2013-09-30-2.jpg TEST_PATH/2013/2013-09-30-2.jpg 
TEST_PATH/2013/2013-09-30-2.jpg 
TEST_PATH/2013/2013-09-30-2.jpg 

File number: 4 June 21 2017.txt TEST_PATH/2017/June 21 2017.txt 
TEST_PATH/2017/June 21 2017.txt 

回答

1

它移動的文件,因爲你目前的工作目錄的我客串它的工作原理就像mv命令一樣。生成的文件在raname之後,將被放入由os.rename函數的第二個參數指定的路徑,相對於cwd。如果你希望它能正常工作,你需要用新文件名指定相對路徑。

順便說一句。您可以通過這種方式立即執行步驟3 & 4。

+0

現在有了很多意義 - 讓它工作,謝謝! – tkim90