首页 > 解决方案 > 如何防止值以错误的顺序传递到列表中,并且看似随机的数字被附加到每个值?

问题描述

嘿stackoverflow社区!

我正在尝试编写一个程序,该程序可以从文件中读取数据,并以 .csv 文件的形式返回特定的数值,以便将其读入 excel 以供以后使用。我的代码似乎能够很好地读取数据并返回所需的值,但是当它开始填充列表时,事情就会变得一团糟。

我的代码中有什么东西会自动生成不需要的附加组件吗?对此的帮助将不胜感激!

我目前正在使用 python 2.7

我已经尝试下载一个 pip 安装程序来下载 xlwt 库,但我根本无法下载它。在我当前的代码中,我尝试使用 '\n' 作为分隔符以将其从输出中删除,但这对我来说并没有太大的不同。

import os
import csv

os.chdir(r'fileLocation')
# location = str(input("Enter the location of the file: "))
x = {}
y = {}
z = {}

i = 1
with open('fileName.txt') as f:
    for line in f:
        if 'Location in file of desired data' in line:
            for line in f:
                if 'Height: ' in line:
                    a = line
                    a = a.replace('Height: ', '')
                    x[i] = a
                    print x[i]

                if 'X: ' in line:
                    a = line
                    a = a.replace('X: ', '')
                    y[i] = a
                    print y[i]

                if 'Y: ' in line:
                    a = line
                    a = a.replace('Y: ', '')
                    z[i] = a
                    print z[i]

                i = i + 1
s = [(x), (y), (z)]
print(s)

with open('data.csv', 'w') as csvFile:
    wr = csv.writer(csvFile, delimiter = '\n', quoting = csv.QUOTE_ALL)
    wr.writerows([s])

我希望我的输出列表看起来像[1 2 3; 4 5 6; 7 8 9],但在阅读和填充列表之间变得混乱 - 它看起来更像[{204: '2\n' 1: '3\n' 201: '1\n'; 203: '2\n' 12: '3\n' 201: '1\n'; 24: '2\n' 51: '3\n' 1: '1\n'}]

标签: pythoncsv

解决方案


x,y并被z声明为字典,它们的声明为{}和使用x[i]=a。在这种情况下,i是 csv 行的编号。您可以在读取文件之前声明一个列表。

你有\n你的最终打印,因为你没有转换结果。这可以通过int()函数来​​完成

如果你想拥有sequals [[1, 2, 3], [4, 5, 6]],你只需要这样做:

import os
import csv

os.chdir(r'fileLocation')
# location = str(input("Enter the location of the file: "))

x = []
y = []
z = []
with open('fileName.txt') as f:
    for line in f:
        if 'Location in file of desired data' in line:
            for line in f:
                if 'Height: ' in line:
                    x.append(float(line.replace('Height: ', '')))
                    print a

                if 'X: ' in line:
                    y.append(float(line.replace('X: ', '')))
                    print a

                if 'Y: ' in line:
                    z.append(float(line.replace('Y: ', '')))
                    print a
s = [x, y, z]
print(s)

with open('data.csv', 'w') as csvFile:
    wr = csv.writer(csvFile, delimiter = '\n', quoting = csv.QUOTE_ALL)
    wr.writerows([s])

编辑:替换int()为,float()因为 csv 中有浮点值。


推荐阅读