2013-05-14 50 views
0

Ruby的新手,可能有點愚蠢用mkdir創建目錄時遇到麻煩

試圖創建一個目錄以便在其中存儲文件。這裏是我的代碼,這樣做

def generateParsedEmailFile 
    apath = File.expand_path($textFile) 
    filepath = Pathname.new(apath + '/' + @subject + ' ' + @date) 
    if filepath.exist? 
     filepath = Pathname.new(filepath+ '.1') 
    end 
    directory = Dir.mkdir (filepath) 
    Dir.chdir directory 
    emailText = File.new("emailtext.txt", "w+") 
    emailText.write(self.generateText) 
    emailText.close 
    for attachment in @attachments 
     self.generateAttachment(attachment,directory) 
    end 
end 

這裏的錯誤,我得到的

My-Name-MacBook-2:emails myname$ ruby etext.rb email4.txt 
etext.rb:196:in `mkdir': Not a directory - /Users/anthonydreessen/Developer/Ruby/emails/email4.txt/Re: Make it Brief Report Wed 8 May 2013 (Errno::ENOTDIR) 
    from etext.rb:196:in `generateParsedEmailFile' 
    from etext.rb:235:in `<main>' 
+0

'$ textFile'確實需要是一個全局變量嗎?通常沒有必要。 – tadman 2013-05-14 00:21:25

+0

您期望的示例文件夾名稱? – matzone 2013-05-14 00:23:23

+0

變量的值是什麼?從錯誤,它看起來像apath =「/Users/myname/Developer/Ruby/emails/email4.txt」,主題=「正確的主題」和日期=「正確的日期」 – datguy 2013-05-14 00:29:44

回答

3

我能夠重新創建錯誤 - 它看起來像email4.txt是一個普通的文件,而不是一個目錄,所以你不能使用它作爲你的目錄路徑的一部分。

1

你有正確的想法,而應該是更具體的瞭解你打開的文件。更改當前的工作目錄非常麻煩,因爲它會在整個過程中改變它,並可能導致應用程序的其他部分崩潰。

require 'fileutils' 

def generate_parsed_email_file(text_file) 
    path = File.expand_path("#{@subject} #{date}", text_file) 

    while (File.exist?(path)) 
    path.sub!(/(\.\d+)?$/) do |m| 
     ".#{m[1].to_i + 1}" 
    end 
    end 

    directory = File.dirname(path) 
    unless (File.exist?(directory)) 
    FileUtils.mkdir_p(directory) 
    end 

    File.open(path, "w+") do |email| 
    emailText.write(self.generateText) 
    end 

    @attachments.each do |attachment| 
    self.generateAttachment(attachment, directory) 
    end 
end 

我冒昧使這個例子更顯著紅寶石般的:

  • 的方法使用混合大小寫的名字是非常不規則,全局變量皺起了眉頭。
  • 使用for極其罕見,each更靈活。
  • 如果文件可以打開,File.open方法會產生一個塊,並在塊完成時自動關閉。
  • 「.1」部分已擴展爲保持循環,直到找到未使用的名稱。
  • FileUtils用於確保創建完整路徑。
  • 全局變量已轉換爲參數。
+0

的一部分。發生同樣的錯誤 – Pinwheeler 2013-05-14 00:41:15

+0

不錯。進一步的改進要考慮:除非存在測試來保護'mkdir_p',否則不需要。 Ruby 2現在有['File :: write'](http://www.ruby-doc.org/core-2.0/IO.html#method-c-write),當您只想將字符串轉儲到文件一槍。 – dbenhur 2013-05-14 00:44:22

+0

我錯了,在File.open中發生錯誤讓我看看我是否做了其他錯誤 – Pinwheeler 2013-05-14 00:47:02

2

如果您切換到mkdir_p,並得到了同樣的錯誤,也許在'/Users/anthonydreessen/Developer/Ruby/emails/email4.txt/Re: Make it Brief Report Wed 8 May 2013'命名父母一方已存在的常規文件,不能像對待目錄。可能是最後一個名爲email.txt

+0

哦哇...感謝您的疑難解答。這是一個令人尷尬的問題 – Pinwheeler 2013-05-14 00:54:47

+1

樂意提供幫助。 (不要過於羯磨妓女,但我有點困惑,爲什麼datguy得到的信譽,當我的答案確定問題早於他一個小時。) – dbenhur 2013-05-14 02:56:05

+0

我看到datguy比你更少的業力,他早些時候在幫忙以及。我有點覺得,當你超過5K時,積分並不意味着太多。我希望我沒有犯錯。 – Pinwheeler 2013-05-14 22:55:19