logo

How to Read Text (txt) Files as Strings in Julia 📂Julia

How to Read Text (txt) Files as Strings in Julia

Description

There are several ways to load a text file. A simple approach is to use the functions read(), readline(), and readlines(). Among these, read() reads the entire file and returns a string, readline() reads the first line from the file and returns a string, and readlines() reads all lines of the file and returns a vector whose elements are the strings of each line. If you do not specify a type when using read(), it will be loaded as UInt8, so if you want to load it as a string, don’t forget to pass String. Suppose a file named IveandLesserafim.txt contains the following content.

IVE
안유진
가을
레이
장원영
리즈
이서
LESSERAFIM
김채원
사쿠라
허윤진
카즈하
홍은채

Code

julia> read("IveandLesserafim.txt")
124-element Vector{UInt8}:
 0x49
 0x56
 0x45
    
 0xec
 0xb1
 0x84

julia> read("IveandLesserafim.txt", String)
"IVE\r\n안유진\r\n가을\r\n레이\r\n장원영\r\n리즈\r\n이서\r\nLESSERAFIM\r\n김채원\r\n사쿠라\r\n허윤진\r\n카즈하\r\n홍은채"

julia> readline("IveandLesserafim.txt")
"IVE"

julia> readlines("IveandLesserafim.txt")
13-element Vector{String}:
 "IVE"
 "안유진"
 "가을"
 "레이"
 "장원영"
 "리즈"
 "이서"
 "LESSERAFIM"
 "김채원"
 "사쿠라"
 "허윤진"
 "카즈하"
 "홍은채"

See also

Environment

  • OS: Windows11
  • Version: Julia 1.11.3