将列表导出为 CSV

Exporting lists to CSV

在 Python 中,我正在尝试将自定义音乐调谐程序的数据导出为 CSV。


这是我的目标(第 1 列从 0-127,第 2 列是表示为频率的音高列表)。 The Goal

我只需要删除第一行。 Where I'm at


这个线程中的对话对我帮助很大。 Writing data into CSV file

在使用该线程中的代码时,我在 Python Visualizer 中实现了我的目标,但只是部分代码。

Visualizer Example

我所有的代码:

# Ask user for the Home Frequency

print('What is your home frequency?')
raw_tonic = input()
t = int(raw_tonic)


# Ask user for an EDO

print('how many notes per octave do you want?')
raw_edo = input()
e = int(raw_edo)

# Spit out these frequencies into CSV



import csv

myFile = open("edotest9.csv", "w", newline="")

row = []
count = 0
writer = csv.writer(myFile)
row1 = []
for n in range(1, 129):
    for i in range(1, 2):
        row1.append(((t*2**((n-69)/e))))
    count = count + 1
    print(row1)
    writer.writerow(row1)
    row1[:] = [n]


myFile.close()

    for i in range(1, 2):
        row1.append(((t*2**((n-69)/e))))

此行将第一行添加到您的 csv 输出。我假设如果您删除它,那么您将获得目标输出。

在 python 中编写 CSV 的一般过程如下:

  1. Construct a 2D array. Each array in this 2D array represents your row in a CSV.
  2. Create CSV file by feeding this 2D array to the writerows method like I did below.

代码:

import csv

# Ask user for the Home Frequency
t = int(input('What is your home frequency?: '))

# Ask user for an EDO
e = int(input('how many notes per octave do you want?: '))

# Split out these frequencies into CSV
rows = []
column2_diff_pattern = [3, 3, 2, 3, 3, 3, 2]
diff_pattern_length = len(column2_diff_pattern)
column2 = 0
pattern_index = 0
for n in range(1, 129):
    row = [n, t*2**((column2-69)/e)]
    rows.append(row)
    column2 = column2 + column2_diff_pattern[pattern_index]
    pattern_index = (pattern_index + 1) % diff_pattern_length
    
# Do 'rows = rows[1:]' for removing the first row

with open('edotest9.csv', 'w') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerows(rows)