Does Julia have a same way to read and write data (Array & String) as Python?

Viewed 402

I've used Python to analyze simulation data until now, but sometimes it's slower than I expected. So, I've been trying to use Julia these days, but It's hard for me to get familiar with it and also get information as much as python. That's why I am here for help!

Q1. The best way to import array directly from a file and export array to a file in Julia (I've used "numpy genfromtxt" & "numpy savetxt" in python) Q2. The best way to read strings and export these as string but also use specific format ('%10.3f' %, rjust, ljust so on.) in Julia

To understand my question properly, I also leave python code for the question.

Q1. The best way to import array directly from a file and export array to a file.

This array is in the test.txt file
  1.1     -399.16
  1.2     -398.21
  2.4     -399.59
  4.5     -401.51
  2.2    -1071.64
  2.3    -1074.35
  5.5    -1077.36
  9.7    -1069.9
  14.0    -1731.35
  14.2    -1739.84

import numpy as np
data = np.genfromtxt('D:\\JULIA\\test.txt')
np.savetxt('D:\\JULIA\\outdata.txt', data, fmt="%10.3f")

Q2. The best way to read strings and export these as string but use specifit format ('%10.3f' %, rjust, ljust so on.)

data = open('D:\\JULIA\\test.txt','r')
outdata = open('D:\\JULIA\\outdata.txt','w')
lines= data.readlines()
for line in lines:
    splitline  = line.split()
    col1 = float(splitline[0])
    col2 = float(splitline[1])
    outdata.write(('%10.3f' % col1).rjust(20) +', ' +('%10.3f' %col2).rjust(40)+'\n')
data.close()
outdata.close()

Please answer me if there are the same or similar ways in Julia or just different way should be used in Julia.

1 Answers

There are multiple ways to achieve the same result in Julia. The most natural given your experience with np.savetxt is probably the DelimitedFiles standard library:

using DelimitedFiles

data = readdlm("input.txt")

writedlm("output.txt", data)

Check the documentation of these functions for more details. Alternatively, there are various packages for saving data to disk such as JLD.jl, JLD2.jl, BSON.jl, HD5F.jl, ... The list is enormous.

Related