2017-01-02 30 views
2

我充滿了5個文件,沒有文件類型(也許他們的文件類型是「名爲.txt」 - 我不確定)的目錄中,命名爲‘文件1’,‘文件2’......當所有文件都沒有類型時,在Ruby中更改文件名?

我想將它們轉換爲CSV格式用下面的代碼:

require('fileutils') 
folder_path = "correct_folder_path" 
Dir.foreach(folder_path) do |f| 
    next if f == '.' || f == '..' 
    #confirm inputs are correct (they are) 
    #p f 
    #p f+".csv" 
    File.rename(f, f+".csv") 
end 

我已經p'd輸出F以確認一切正常,但行

File.rename(f,f+".csv") 

拋出錯誤:在'重命名'」:沒有這樣的文件或目錄...(Errno :: ENOENT)「

有誰知道爲什麼這不起作用?

回答

2

隨着風向和文件

你可以將目錄更改folder_path。如果某些文件可能已經「名爲.txt」擴展名,您需要先刪除擴展爲了不得到.txt.csv文件:

folder_path = "correct_folder_path" 
Dir.chdir(folder_path) do 
    Dir.foreach(".") do |f| 
    next if File.directory?(f) 
    basename = File.basename(f, '.*') 
    new_file = basename + '.csv' 
    p f 
    p new_file 
    ## Uncomment when you're sure f and new_file are correct : 
    # File.rename(f, new_file) unless f == new_file 
    end 
end 

隨着路徑名

隨着Pathname,它通常更容易過濾和重命名文件:

require 'pathname' 
folder_path = "correct_folder_path" 

Pathname.new(folder_path).children.each do |f| 
    next if f.directory? 
    p f 
    p f.sub_ext('.csv') 
    ## Uncomment if you're sure f and subext are correct : 
    # f.rename(f.sub_ext('.csv')) 
end 
2

通過Dir.foreach返回的路徑是相對於您在通過folder_path。您對File.rename電話試圖重命名當前的工作目錄,這可能不是同一個目錄中,通過folder_path指定的文件。

您可以重命名通過預先folder_path到文件名成功:

f = File.join(folder_path, f) 
File.rename(f, f + ".csv") 
1

一種選擇:

require 'pathname' 

folder.children.each do |child| 
    # Other logic here 
    child.rename(child.dirname + (child.basename.to_s + '.csv')) 
end 
相關問題