我正在尝试从.txt
文件中读取值并将它们写入另一个.txt
文件中,每行一个值,并且索引之间用逗号分隔。我陷入困境是因为当我在新文件中写入值时,我还用第一个值写入字符[
,而最后一个写入字符\n]
。
我想念什么?如何只写值?
问题出在第一个函数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是有用的链接
答案 0 :(得分:0)
基于您链接的文件,我没有看到任何'\ n'或'[',相反,您是通过将列表直接转换为字符串而得到的,字符串保留了所有内容。
将数据转换为字符串,然后立即将其连接并拆分可解决此问题。
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()