蓝色天空网mbsky.com · 知识 · 实践 · 创造Julia · 本地阅读预览
教程 / Python / 数据科学 / Julia

Julia 文件读写与路径

对临时文件实测六种打开模式、字节和逐行读取、路径操作及本机 HTTP 下载。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

流、打开模式和关闭

open 返回可读取或写入的 IOStream。文件句柄用于关联底层打开资源,读写位置可以随操作改变。用 close 释放资源,或用 open 的 do 形式自动关闭。模式决定读写、缺失文件是否创建、打开时是否截断,以及写入是否追加。

本站在隔离目录分别以字符串模式和关键字选项打开已有文件和缺失路径,再观察权限、定位、写入和最终内容。对已存在的文件使用 w 或 w+ 时,截断发生在打开时。追加模式打开时位置在文件末尾。Julia 1.10.13 Windows 的 a 与 a+ 在显式 seekstart 后写入会覆盖起始字节。未重定位时再写,实测数据追加到末尾。

写入、读取与逐行处理

write 返回写入字节数,中文等 UTF-8 内容的字节数与 Char 数可以不同。close 会结束流,flush 可将流中的缓冲写出。两者都不能单独保证断电后数据已经持久化。

read(io,String) 或 read(path,String) 读出文本。readlines 可一次得到各行,keep=true 保留行末。eachline 按需迭代,适合较大文件;也可用 eof 与 readline 控制行号。例程用同一文件核对 CRLF、LF 以及多字节字符。

路径、文件属性和下载

stat 返回文件属性,filesize、isfile、isdir 可查询单项。字段如设备编号、所有者和时间随平台和实际文件而变。joinpath 组装路径,abspath 从当前目录起算,normpath 只做路径规范化,realpath 处理现有路径。

复制、移动和删除例程只操作本轮创建的临时样本。历史 Base.download 的用途是把网络资源保存为文件。新代码可使用标准库 Downloads.download。本章两个接口都只访问 127.0.0.1 上本站例程创建的 HTTP 样本。

六种文件模式

模式实际行为等效关键字
r只读,文件须存在。默认,无关键字。
w写入,缺失时创建,已有文件在打开时截断。write=true
a写入,缺失时创建,打开后定位到末尾。本站测试环境中,显式定位仍会改变写入位置。append=true
r+读写,文件须存在。既不截断也不强制追加。read=true, write=true
w+读写,缺失时创建,已有文件截断。truncate=true, read=true
a+可读写,缺失时创建,初始位置在末尾。本站测试环境中,显式定位仍会改变写入位置。append=true, read=true

路径与文件操作

序号接口含义
1cd(path)切换工作目录。do 形式结束后恢复此前目录。
2pwd()返回当前工作目录。
3readdir(path)列出目标目录的文件和子目录名称。
4abspath(path)将路径按当前目录解析为绝对形式。
5joinpath(parts...)按平台路径规则拼接各段。
6isdir(path)判断目标是否是目录。
7splitdir(path)拆成目录部分和末段。
8splitdrive(path)Windows 拆分驱动器和路径。普通相对路径的驱动器部分为空。
9splitext(path)拆出末段的最后一个扩展名,保留扩展名的点。
10expanduser(path)在支持该行为的平台展开开头的 ~。Windows 行为见本机检查。
11normpath(path)规范化分隔符与路径段,本身无需目标存在。
12realpath(path)获取现有路径的实际规范路径。
13homedir()获得当前用户的主目录路径。
14dirname(path)返回目录部分。
15basename(path)返回路径末段。
16cp(src,dst)复制文件。源文件仍存在。
17mv(src,dst)移动或重命名文件。
18rm(path)删除已知目标,递归选项适用于确认过范围的目录。
19mkdir(path) / mkpath(path)分别创建一层或补全多层目录。
20Downloads.download(url, output)从 URL 写入本地文件。历史 Base.download 和现行接口均用本机 HTTP 样本核对。

文件实例:检查模式、UTF-8 行和本机下载

julia · 阅读源码

using Downloads, Sockets, SHA
include(joinpath(@__DIR__, "observations.jl"))

function observe_mode(opener,existing,missing)
    write(existing,"ABCD")
    reading,writing,initial,before,read_after = opener(existing) do io
        reading,writing=isreadable(io),iswritable(io)
        initial=position(io)
        seekstart(io)
        before=reading ? read(io,String) : nothing
        if writing
            seekstart(io)
            write(io,"Z")
            flush(io)
        end
        seekstart(io)
        (reading,writing,initial,before,reading ? read(io,String) : nothing)
    end
    failure=outcome() do
        opener(missing) do io
            iswritable(io) && write(io,"N")
        end
    end
    (reading,writing,initial,before,read_after,read(existing,String),failure,
     isfile(missing) ? read(missing,String) : nothing)
end

function exercise_mode(root,label,mode,keywords,expected)
    first=observe_mode((f,p)->open(f,p,mode),joinpath(root,label*"mode"),joinpath(root,label*"mode-new"))
    second=observe_mode((f,p)->open(f,p;keywords...),joinpath(root,label*"kw"),joinpath(root,label*"kw-new"))
    probe("file_mode_"*label,(mode,keywords,"ABCD and missing file; seekstart before write"),(first,second),(expected,expected))
end

function local_fixture(root)
    fixture="Station 海\n"
    payload=codeunits(fixture)
    server=listen(ip"127.0.0.1",0)
    endpoint="http://127.0.0.1:$(getsockname(server)[2])/fixture"
    requests=String[]
    handler=@async for _ in 1:2
        conn=accept(server)
        try
            push!(requests,readline(conn))
            while !isempty(readline(conn))
            end
            write(conn,"HTTP/1.1 200 OK\r\nContent-Length: $(length(payload))\r\nConnection: close\r\n\r\n")
            write(conn,payload)
        finally
            close(conn)
        end
    end
    try
        direct=Downloads.download(endpoint,joinpath(root,"modern.txt");timeout=8)
        historical=Base.download(endpoint,joinpath(root,"historical.txt"))
        wait(handler)
        probe("file_download","two loopback HTTP GET requests",
              (requests,read(direct,String),read(historical,String),sha256(read(direct))==sha256(payload)),
              (["GET /fixture HTTP/1.1","GET /fixture HTTP/1.1"],fixture,fixture,true))
    finally
        close(server)
    end
end

mktempdir() do root
    exercise_mode(root,"r","r",(;),(true,false,0,"ABCD","ABCD","ABCD","SystemError",nothing))
    exercise_mode(root,"w","w",(write=true,),(false,true,0,nothing,nothing,"Z","no error","N"))
    exercise_mode(root,"a","a",(append=true,),(false,true,4,nothing,nothing,"ZBCD","no error","N"))
    exercise_mode(root,"rplus","r+",(read=true,write=true),(true,true,0,"ABCD","ZBCD","ZBCD","SystemError",nothing))
    exercise_mode(root,"wplus","w+",(truncate=true,read=true),(true,true,0,"","Z","Z","no error","N"))
    exercise_mode(root,"aplus","a+",(append=true,read=true),(true,true,4,"ABCD","ZBCD","ZBCD","no error","N"))

    append_file=joinpath(root,"append.txt")
    write(append_file,"ABCD")
    open(append_file,"a") do io
        write(io,"Z")
    end
    probe("file_append_at_open","no repositioning before write",read(append_file,String),"ABCDZ")

    file=joinpath(root,"stations.txt")
    io=open(file,"w")
    bytes=write(io,"North\r\n海\nLast")
    close(io)
    probe("file_manual_close","write UTF-8 then close",(bytes,!isopen(io),read(file,String)),
          (15,true,"North\r\n海\nLast"))
    handle=Ref{IO}()
    status=outcome() do
        open(file,"a") do stream
            handle[]=stream
            write(stream,"\n")
            error("test cleanup")
        end
    end
    probe("file_do_close","append LF and throw", (status,!isopen(handle[]),read(file,String)),
          ("ErrorException",true,"North\r\n海\nLast\n"))
    simple=joinpath(root,"copy-source.txt")
    size=write(simple,"Harbor 海")
    probe("file_write","Harbor 海",(size,read(simple,String),read(simple)==collect(codeunits("Harbor 海"))),
          (10,"Harbor 海",true))
    manual=open(file)
    from_stream=read(manual,String)
    close(manual)
    from_do=open(f->read(f,String),file)
    probe("file_read","read whole file three ways",(from_stream,from_do,read(file,String)),
          ("North\r\n海\nLast\n","North\r\n海\nLast\n","North\r\n海\nLast\n"))
    with_lines=open(f->readlines(f;keep=true),file)
    probe("file_readlines","CRLF, LF, LF",(with_lines,readlines(file)),
          (["North\r\n","海\n","Last\n"],["North","海","Last"]))
    streamed=open(file) do f
        [(length(line),ncodeunits(line),line) for line in eachline(f)]
    end
    probe("file_eachline","three UTF-8 lines",streamed,[(5,5,"North"),(1,3,"海"),(4,4,"Last")])
    numbered=open(file) do f
        result=Tuple{Int,String}[]
        line=1
        while !eof(f)
            push!(result,(line,readline(f)))
            line+=1
        end
        result
    end
    probe("file_readline","number each line until EOF",numbered,[(1,"North"),(2,"海"),(3,"Last")])
    metadata=stat(file)
    probe("file_stat","station file",
          (metadata.size,filesize(file),isfile(file),isdir(root),:mtime in fieldnames(typeof(metadata)),
           isfinite(metadata.mtime)),(16,16,true,true,true,true))

    before=pwd()
    inside=cd(root) do
        pwd()
    end
    probe("file_cd","temporarily enter exercise directory",(realpath(inside)==realpath(root),pwd()==before),(true,true))
    probe("file_pwd","current project path",(isabspath(pwd()),isdir(pwd())),(true,true))
    sub=joinpath(root,"sub")
    mkdir(sub)
    leaf=joinpath(sub,"deep","inside")
    mkpath(leaf)
    probe("file_readdir","sub directory and two seed files",all(name->name in readdir(root),["sub","stations.txt","copy-source.txt"]),true)
    abs_names=cd(root) do
        map(abspath,readdir())
    end
    probe("file_abspath","convert names from exercise directory",
          (all(isabspath,abs_names),file in abs_names),(true,true))
    probe("file_joinpath",("sub","deep","inside"),joinpath(sub,"deep","inside")==leaf,true)
    probe("file_isdir","directory and regular file",(isdir(leaf),isdir(file)),(true,false))
    probe("file_splitdir","stations.txt",(dirname(file)==root,splitdir(file)==(root,"stations.txt")),(true,true))
    probe("file_splitdrive","Windows drive and path",(splitdrive(raw"C:\demo\sample.txt"),splitdrive("local.txt")),
          ((raw"C:",raw"\demo\sample.txt"),("","local.txt")))
    probe("file_splitext","last extension",(splitext("archive.tar.gz"),splitext("station")), (("archive.tar",".gz"),("station","")))
    probe("file_expanduser","tilde behavior",(expanduser("ordinary.txt"), Sys.iswindows() ? expanduser("~")=="~" : expanduser("~")==homedir()),
          ("ordinary.txt",true))
    probe("file_normpath","dot and parent segments",normpath(joinpath(sub,".","..","stations.txt"))==file,true)
    probe("file_realpath","existing path, including parent segments",realpath(joinpath(sub,"..","stations.txt"))==realpath(file),true)
    probe("file_homedir","home directory path form without reading its contents",(isabspath(homedir()),isdir(homedir())),(true,true))
    probe("file_dirname","station file",dirname(file)==root,true)
    probe("file_basename","station file",basename(file),"stations.txt")
    copy_path=joinpath(leaf,"copy.txt")
    cp(simple,copy_path)
    probe("file_cp","copy locally",(read(copy_path,String),isfile(simple)),("Harbor 海",true))
    moved=joinpath(leaf,"moved.txt")
    mv(copy_path,moved)
    probe("file_mv","move within fixture",(isfile(copy_path),isfile(moved),read(moved,String)),(false,true,"Harbor 海"))
    @assert dirname(realpath(moved))==realpath(leaf)
    rm(moved)
    probe("file_rm","remove one known fixture file",isfile(moved),false)
    probe("file_mkdir","single and nested directories",(isdir(sub),isdir(leaf)),(true,true))
    local_fixture(root)
end
预期结果 · 待实际运行核验
  • r+ 在起始位置改写得到 ZBCD,w+ 截断后得到 Z。逐行读取时可选择是否保留 CRLF 或 LF。两个本机 HTTP 下载都返回同一份 UTF-8 数据。
文件实例:检查模式、UTF-8 行和本机下载

所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录

当前源码 SHA256:2c7f6e13f8acf58c945984231f87d594f4ff47db3e91c90e5829f0ac18fc1a62

下载本站示例源码

本机练习工程

解压后按 README 运行。文件例程仅操作临时文件和本机 HTTP 测试数据。

下载本站 Julia 日期、文件与元编程练习

所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录

ZIP SHA256:abcef04c9e28ed0a507db667c68dfcb51d6f7c21c25aa4fa3abbdd59c6f9fa3f

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

如何让缺失文件得到默认内容,同时保留既有文件内容?

展开参考解答

选择符合需求的追加或显式创建流程,并先用临时样本验证写入位置。

规范与官方依据