แพ็กเกจ os และ filepath
ตัวแปรสภาพแวดล้อม เส้นทาง และการโต้ตอบกับระบบปฏิบัติการ
แพ็กเกจ os และ filepath เป็นบทเรียน Go Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Go Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Go Academy มีบทเรียนทั้งหมด 4 บทเรียน
os.Args — อาร์กิวเมนต์บรรทัดคำสั่ง
os.Args เก็บอาร์กิวเมนต์บรรทัดคำสั่งไว้ โดย os.Args[0] คือชื่อโปรแกรม:
package main
import ("fmt"; "os")
func main() {
fmt.Println("Program:", os.Args[0])
if len(os.Args) < 2 {
fmt.Println("Usage: program <name>")
os.Exit(1)
}
fmt.Printf("Hello, %s!\n", os.Args[1])
}os.Getenv และ os.Setenv
อ่านและเขียนตัวแปรสภาพแวดล้อม:
package main
import ("fmt"; "os")
func main() {
// Read env var (returns "" if not set)
home := os.Getenv("HOME")
fmt.Println("HOME:", home)
// Set env var
os.Setenv("APP_ENV", "production")
fmt.Println(os.Getenv("APP_ENV")) // production
// Get with default pattern:
port := os.Getenv("PORT")
if port == "" { port = "8080" }
fmt.Println("Port:", port)
}os.Exit — ยุติโปรแกรม
os.Exit ยุติโปรแกรมพร้อมรหัสสถานะ โดยรหัส 0 หมายถึงสำเร็จ และค่าที่ไม่ใช่ศูนย์หมายถึงข้อผิดพลาด ฟังก์ชันที่เลื่อนการทำงานไว้จะ NOT ทำงาน:
package main
import ("fmt"; "os")
func main() {
config := os.Getenv("CONFIG_PATH")
if config == "" {
fmt.Fprintln(os.Stderr, "error: CONFIG_PATH not set")
os.Exit(1) // signals error to the shell
}
fmt.Println("config:", config)
}os.Open, os.Create, os.ReadFile
การดำเนินการกับไฟล์ด้วยแพ็กเกจ os:
package main
import ("fmt"; "os")
func main() {
// Read entire file
data, err := os.ReadFile("/etc/hostname")
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("hostname: %s", data)
// Write file (overwrites if exists)
err = os.WriteFile("/tmp/test.txt", []byte("hello\n"), 0644)
fmt.Println("write err:", err)
}os.Stat — ข้อมูลไฟล์
os.Stat ส่งคืนข้อมูลเกี่ยวกับไฟล์หรือไดเรกทอรี:
package main
import ("fmt"; "os")
func main() {
info, err := os.Stat("/tmp")
if err != nil {
if os.IsNotExist(err) {
fmt.Println("does not exist")
}
return
}
fmt.Println(info.Name()) // tmp
fmt.Println(info.IsDir()) // true
fmt.Println(info.Size()) // size in bytes
fmt.Println(info.Mode()) // file permissions
fmt.Println(info.ModTime()) // last modified time
}os.MkdirAll และ os.RemoveAll
สร้างและลบโครงสร้างไดเรกทอรี:
package main
import ("fmt"; "os")
func main() {
// Create nested directories
err := os.MkdirAll("/tmp/myapp/data/logs", 0755)
fmt.Println("mkdir:", err)
// Remove a file
err = os.Remove("/tmp/test.txt")
fmt.Println("remove:", err)
// Remove directory and all contents
err = os.RemoveAll("/tmp/myapp")
fmt.Println("removeAll:", err)
}path/filepath: เส้นทางข้ามแพลตฟอร์ม
path/filepath จัดการเส้นทางไฟล์โดยใช้ตัวคั่นเส้นทางของระบบปฏิบัติการ (/ บน Unix และ \ บน Windows):
package main
import ("fmt"; "path/filepath")
func main() {
// Join path components correctly
p := filepath.Join("/home", "user", "docs", "file.txt")
fmt.Println(p) // /home/user/docs/file.txt
// Split path and file
dir, file := filepath.Split(p)
fmt.Println(dir, file) // /home/user/docs/ file.txt
// Extension
fmt.Println(filepath.Ext(p)) // .txt
// Base name
fmt.Println(filepath.Base(p)) // file.txt
}filepath.Walk — สำรวจไดเรกทอรี
เดินสำรวจโครงสร้างไดเรกทอรีโดยเยี่ยมชมไฟล์และไดเรกทอรีทุกแห่ง:
package main
import ("fmt"; "os"; "path/filepath")
func main() {
err := filepath.Walk("/tmp", func(path string, info os.FileInfo, err error) error {
if err != nil { return err }
if info.IsDir() {
fmt.Println("[DIR]", path)
} else {
fmt.Printf("[FILE] %s (%d bytes)\n", path, info.Size())
}
return nil
})
if err != nil { fmt.Println("walk error:", err) }
}filepath.Glob — การจับคู่รูปแบบ
ค้นหาไฟล์ที่ตรงกับรูปแบบ glob:
package main
import ("fmt"; "path/filepath")
func main() {
// Find all .go files in current directory
matches, err := filepath.Glob("*.go")
if err != nil {
fmt.Println(err)
return
}
for _, m := range matches {
fmt.Println(m)
}
// Absolute path resolution
abs, _ := filepath.Abs("../myfile.txt")
fmt.Println(abs)
}os.TempDir และ os.CreateTemp
สร้างไฟล์ชั่วคราวอย่างปลอดภัย:
package main
import ("fmt"; "os")
func main() {
// System temp directory
fmt.Println(os.TempDir()) // /tmp
// Create a unique temp file
f, err := os.CreateTemp("", "myapp-*.json")
if err != nil {
fmt.Println(err)
return
}
defer os.Remove(f.Name()) // clean up
defer f.Close()
fmt.Println("temp file:", f.Name())
_, _ = f.WriteString(`{"status":"ok"}`)
}ตรวจสอบความเข้าใจ
ฟังก์ชันใดรวมส่วนประกอบของเส้นทางไฟล์ได้อย่างถูกต้องและรองรับการใช้งานข้ามแพลตฟอร์ม
ทบทวน: os และ filepath
สรุป:
os.Args— อาร์กิวเมนต์คำสั่ง และos.Getenv/Setenv— สภาพแวดล้อมos.ReadFile/WriteFileสำหรับการรับส่งข้อมูลกับไฟล์แบบง่ายos.Stat— ข้อมูลไฟล์ และos.IsNotExist(err)สำหรับไฟล์ที่ไม่มีอยู่os.MkdirAll/RemoveAllสำหรับจัดการไดเรกทอรีfilepath.Join/Split/Ext/Baseสำหรับเส้นทางข้ามแพลตฟอร์มfilepath.Walkสำหรับสำรวจโครงสร้างไดเรกทอรี
เรียนรู้ Go ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 51
- บทเรียน
- 203
คำถามที่พบบ่อย
บทเรียน “แพ็กเกจ os และ filepath” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “แพ็กเกจ os และ filepath” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Go Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Go Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “แพ็กเกจ os และ filepath”
ตัวแปรสภาพแวดล้อม เส้นทาง และการโต้ตอบกับระบบปฏิบัติการ คุณปฏิบัติ Go Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Go Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Go Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “แพ็กเกจ os และ filepath” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Go Academy นี้ได้ไหม
ได้ บทเรียน Go Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- แพ็กเกจ fmt และ strings
- strconv, math และ sort
- พื้นฐานแพ็กเกจ time
- แพ็กเกจ os และ filepath