【问题标题】:How to read a file in Julia like Python如何像 Python 一样在 Julia 中读取文件
【发布时间】:2022-01-06 06:02:31
【问题描述】:

为什么这些有区别?:

# 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)

Python 的输出如下:

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

Julia 的输出如下:

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是这个:

hello World
yay

如您所见,输出不同。我怎样才能让 Julia 的行为像 Python 一样?在 Julia 中还有其他读取文件的方法吗?

【问题讨论】:

    标签: python file julia file-read


    【解决方案1】:

    你可以这样做:

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

    默认情况下,它会丢弃\n,但您可以通过添加keep=true 来保留它们。

    【讨论】:

      【解决方案2】:

      这里是使用 user17558100 的 keep=true 建议的更加朱利安(和更正)的版本:

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

      这种do 格式与Python 的with 语句相同,这样可以确保文件在没有明确的close() 调用的情况下关闭。

      【讨论】:

        【解决方案3】:

        如果你想一次读一个字符,你应该使用readeach,例如

        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
        

        顺便说一句,请注意这不是一种有效的方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-20
          • 2020-01-29
          • 1970-01-01
          • 1970-01-01
          • 2020-10-24
          • 1970-01-01
          • 2021-08-28
          • 2019-09-01
          相关资源
          最近更新 更多