0

I am trying to load a data file that is two columns of data, separated by a comma using: Data = np.loadtxt('real3kHz.dat'), where real3kHz.dat is the name of the file with the following data:

4998.29641,-0.00003
4997.33205,-0.00005
4996.36768,-0.00007
4995.40332,-0.00008
4994.43895,-0.00008
4993.47459,-0.00008
4992.51023,-0.00006
4991.54586,-0.00006
4990.5815,-0.00005
4989.61714,-0.00006
 ....

However, I keep getting the following error:

ValueError: could not convert string to float: '4998.29641,-0.00003'

I presumed that I successfully changed the cvs file into a .dat file (by saving it as a .dat file in notepad) before loading it into python. Can I get some help understanding where I am going wrong? Thank you in advance

Ankur
  • 1,030
  • 10
  • 18
jojo
  • 41
  • 1
  • 1
  • 9
  • Can you [edit] to post a few lines from the .dat file? It sounds like it is CSV formatted. – Gino Mempin Jan 21 '21 at 23:58
  • Hello thank you for your response. I have edited the question to include some of the data. I did in fact load the cvs into notepad and saved it as .dat file before loading into python, I am not sure if that was sufficient – jojo Jan 22 '21 at 00:10
  • 1
    Does `np.loadtxt('real3kHz.dat', delimiter=',')` work? – Ankur Jan 22 '21 at 00:17
  • It worked! thank you very much – jojo Jan 22 '21 at 00:20
  • 1
    Does this answer your question? [load csv into 2D matrix with numpy for plotting](https://stackoverflow.com/questions/4315506/load-csv-into-2d-matrix-with-numpy-for-plotting) – mkrieger1 Jan 22 '21 at 00:49
  • I'm not sure why you think the filename extension would make any difference. – Mark Ransom Jan 22 '21 at 00:59
  • If it was originally a CSV file, then simply changing the file extension does not turn it into a .dat file (or whatever format the .dat file is supposed to be). If it was just CSV, just using Python's CSV module could also work. Is there a reason you are loading it with Numpy as `np.loadtxt`? – Gino Mempin Jan 22 '21 at 02:47

1 Answers1

1

Try this and see if it's doing what your asking for :

with open ('real3kHz.dat') as data_file :
for line in data_file :
    line_list = line.strip ('\n').split (',')
    print (f'{float (line_list [0])}   {float (line_list [1]):.5f}')
bashBedlam
  • 1,402
  • 1
  • 7
  • 11