jazz_the_hound
jazz_the_hound

Reputation: 27

read values and write them as comma separated values python

I am trying to read values from a .txt file and write them in another .txt file, one value per row and an index separated by a comma. I get stuck because when I write the values in the new file I also write the character [ with the first value and \n] with the last. What am I missing? How can I write only the values? The issue is in the first function create_csv()

import matplotlib.pyplot as plt
import csv
x = []
y = []

def create_csv():
    index=0
    new_file = open("wv_00_csv.txt", "w+")
    with open('wv_00.txt','r') as f:
        data = f.readlines()
        data1=str(data)
        #new_file.writelines(str(type(data1)))
        #new_file.writelines(str(len(data1)))
        my_var = data1.split(",")
        #new_file.writelines(["%s\n" % item  for item in data1])
        #new_file.writelines(str(my_var))
        #new_file.writelines((my_var))
        #new_file.write("\n")
        for item in my_var:
            new_file.write(item +" , " +str(index))
            new_file.write("\n")
            index+=1
    new_file.close()

def plot():
    with open('wv_00_csv.txt','r') as csvfile:
       plots = csv.reader(csvfile, delimiter=',')
       for row in plots:
          x.append(float(row[1]))
          y.append(float(row[0]))
    plt.plot(x,y, label='Outputwaveform')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('Waveformplot')
    plt.legend()
    plt.show()

create_csv()
#plot()

Here is a link if it is helpful

Upvotes: 1

Views: 686

Answers (1)

GKE
GKE

Reputation: 1000

Based on the file you linked I didn't see any '\n' or '[', instead you got that from converting a list directly into a string, which preserves everything.

Converting the data into a string then immediately joining it and splitting rectifies this issue.

def create_csv():
    index=0
    new_file = open("wv_00_csv.txt", "w+")
    with open('wv_00.txt','r') as f:
        data = f.readline()
        data_string = str(data)
        data_joined = ''.join(data_string)
        data_joined = data_joined.rstrip('\n')
        data_list = data_joined.split(',')
        for item in data_list:
            new_file.write(item + " " + str(index) + '\n')
            index+=1
    new_file.close()

Upvotes: 1

Related Questions