Ruby file操作cheatsheet
每次都要查,真是蛋疼,不如一次性總結(jié)一下,以后再不記得就來(lái)這里找好了。
以下代碼中需要用到的文件名:filename = ‘testfile.txt’
讀取其中的全部?jī)?nèi)容:File.read(filename)
將一個(gè)字符串一次性寫入這個(gè)文件:
File.write(filename, str)讀取文件內(nèi)容,依次處理其中的每一行:
判斷文件是否存在:File.exists?(filename)
刪除文件:File.delete(filename)
文件重命名:File.rename(filename, new_name)
文件的名字:file.path # file是一個(gè)File對(duì)象
文件的絕對(duì)路徑:File.absolute_path(filename)
當(dāng)前所在目錄:Dir.pwd
當(dāng)前登錄用戶的home目錄:Dir.home
創(chuàng)建文件夾:Dir.mkdir(dir_name) #注意,如果父目錄不存在的話,這里無(wú)法創(chuàng)建子目錄
刪除文件夾:Dir.rmdir(dir_name)
創(chuàng)建多級(jí)目錄(mkdir -p):FileUtils.mkdir_p(path) #這里需要require fileutils
找出當(dāng)前目錄下的所有文件或目錄:Dir.glob("*")
找出當(dāng)前目錄下的所有Ruby文件:Dir.glob("*.rb")
判斷目錄是否存在:Dir.exists?(dir_name)
用文件夾和文件組成一個(gè)路徑:File.join(dir_name, filename)
當(dāng)前文件(正在執(zhí)行的文件)相對(duì)于當(dāng)前所在目錄(pwd目錄)的相對(duì)路徑:__FILE__
當(dāng)前文件(正在執(zhí)行的文件)的目錄相對(duì)于當(dāng)前所在目錄(pwd目錄)的相對(duì)路徑:File.dirname(__FILE__)
當(dāng)前文件(正在執(zhí)行的文件)的絕對(duì)路徑:File.expand_path(__FILE__)
當(dāng)前文件(正在執(zhí)行的文件)所在目錄的絕對(duì)路徑:File.expand_path(File.dirname(__FILE__))
最后附上File.open(filename, mode) 中的mode各種取值以及含義:
| "r" | Read-only, starts at beginning of file (default mode). |
| "r+" | Read-write, starts at beginning of file. |
| "w" | Write-only, truncates existing file, to zero length or creates a new file for writing. |
| "w+" | Read-write, truncates existing file to zero lengthor creates a new file for reading and writing. |
| "a" | Write-only, starts at end of file if file exists, otherwise creates a new file for writing. |
| "a+" | Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing. |
| "b" | Binary file mode (may appear with any of the key letters listed above). Suppresses EOL <-> CRLF conversion on Windows. And sets external encoding to ASCII-8BIT unless explicitly specified. |
| "t" | Text file mode (may appear with any of the key letters listed above except "b"). |
有任何意見(jiàn)或建議,或者發(fā)現(xiàn)文中任何問(wèn)題,歡迎留言!
更多文章請(qǐng)?jiān)L問(wèn)個(gè)人博客
作者:鄒小創(chuàng)
Github:https://github.com/ChrisZou
郵件:happystriving@126.com
總結(jié)
以上是生活随笔為你收集整理的Ruby file操作cheatsheet的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [Android] 开源View组件(一
- 下一篇: Node.js进程管理之Process模