Read and write files:
csv JLD2 IOBuffer:
In the operation of the file, if we do not specify the path of the file, the default path is
pwd()commands to view the current working path, if you want to change the path, use the
cd(dir::String)command, if you want to change back to the original path, use the
s1 = readlines("sdy.txt") s2 = open("sdy.txt","r") line = readline(s2) eof(s2) position(s2) read(s2,Char) line = readline(s2) read(s2,Int8) close(s1)
In REPL, you can view the usage of open, and in open, you can also call functions
Of course, you can also call a custom function
readFunc(s::IOStream) = read(s, Char) open(readFunc, "sdy.txt")
You can also
with open...asopen the file like the usage in Python
open("sdy.txt","r") do stream for line in eachline(stream) println(line) end end
You can also define the above process as a function and use the open operation
function readFunc2(stream) for line in eachline(stream) println(line) end end open(readFunc2, "sdy.txt")
write("wrFile1.txt", "Hello World") open("wrFile2.txt","w") do f for ch in'a':'z' write(f, ch) end write(f,'\n') end
The parameter mode in the open function is defined as follows
write, create, truncate
write, create, append
read, write, create, truncate
read, write, create, append
io = open("wrFile3.txt","w") write(io, "Write File...\n")
But this way of reading and writing files does not support matrix operations very well
mat = reshape(1:9, (3,3)) write("mat.txt", mat)
It is best to use
DelimitedFilespackages for matrix read and write operations
using DelimitedFiles m = reshape(1:9, (3,3)) writedlm("number.txt", m,'\t') cont = readdlm("number.txt")
In addition to the txt format, Julia can also support csv and other formats, but Julia's own data serialization tool JLD2 is faster, expands the platform, and is recommended.
Writing csv files is similar to operating ordinary files, just add a comma in the middle.
using DelimitedFiles data = rand(Int8,10,5) writedlm("file1.csv", data,',')
When reading files, we can use DataFrames to read csv files. We will talk about DataFrames in the section on scientific computing.
using DataFrames df = readtable("file1.csv")
You can also use the function that comes with the CSV package to read
using CSV df1 = CSV.read("file1.csv")
The data read by CSV.read() is also in DataFrame format.
JLD2 is an improvement of the JLD format, and it is also a HDF5 format.
using JLD2 stri = "hello world" fid = jldopen("jld_test.jld2","w") write(fid, "stri", stri) close(fid)
fid = jldopen("jld_test.jld2","r") res = read(fid,"ss")
Equivalent to creating an IOStream in memory
io = IOBuffer() write(io, "Hello World!", "JuliaLang is great!")
The method used
take!to read the content from the IOBuffer
If the contents are specified when creating the IOBuffer, the word IOBuffer is read-only.
io = IOBuffer("Hello World!") write(io, "This is not writable.") read(io, String)