Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
How to read a file in Julia like Python

Why is there a difference between these?:

# Python
f = open("./text.txt", "r")
for i in f.readlines():
   for l in i:
      print(print(l == "\n", ":", l))
f.close()
# -----------------------------

# Julia
f = open("./text.txt", "r")
while !eof(f)
    for l in readline(file)
        println(l == '\n', " : ", l)
    end
end
close(f)

The Python one outputs this:

False : h
False : e
False : l
False : l
False : o
False :  
False : W
False : o
False : r
False : l
False : d
True : 
                     <--- yep, it is as expected
False : y
False : a
False : y

The Julia one outputs this:

false : h
false : e
false : l
false : l
false : o
false :         <--- is this not a \n??
false : W
false : o
false : r
false : l
false : d
false : y
false : a
false : y

text.txt is this:

hello World
yay

As you can see the outputs are different. How can I make the Julia one behaves like the Python one? Are there other ways of reading a file in Julia?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

if you like to read a character at a time you should use readeach, e.g.

f = open("./text.txt", "r")
for l in readeach(f, Char)
     println(l == '\n', " : ", l)
end

false : h
false : e
false : l
false : l
false : o
false :  
false : w
false : o
false : r
false : l
false : d
true : 

false : y
false : a
false : y

BTW, just note that this is not an efficient way.

over 4 years ago · Santiago Trujillo Report

0

You can do this:

# Julia
f = open("./text.txt", "r")
while !eof(f)
    for l in readline(file, keep=true)
        println(l == '\n', " : ", l)
    end
end
close(f)

By default, it discards \n's, but you can keep them by adding keep=true.

over 4 years ago · Santiago Trujillo Report

0

Here is a more Julian (and corrected) version using the keep=true suggestion by user17558100:

open("./text.txt", "r") do f
    for l in readlines(f, keep=true)
        foreach(c->println(c == '\n', " : ",c), l)
    end
end

This do format is the same as Python's with statement and this makes sure the file is closed without an explicit close() call.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!