[英]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. 我正在尝试从
.txt
文件中读取值,然后将其写入另一个.txt
文件中,每行一个值,并且索引之间用逗号分隔。 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. 我陷入困境是因为当我在新文件中写入值时,我还用第一个值写入字符
[
,最后一个写入\\n]
。 What am I missing? 我想念什么? How can I write only the values?
如何只写值? The issue is in the first function
create_csv()
问题出在第一个函数
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()
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 . 根据您链接的文件,我没有看到任何'\\ n'或'[',而是从将列表直接转换为字符串(保留了所有内容)后得到的 。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.