python - 如何防止值以错误的顺序传递到列表中,并且看似随机的数字被附加到每个值?
问题描述
嘿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'}]
。
解决方案
x
,y
并被z
声明为字典,它们的声明为{}
和使用x[i]=a
。在这种情况下,i
是 csv 行的编号。您可以在读取文件之前声明一个列表。
你有\n
你的最终打印,因为你没有转换结果。这可以通过int()
函数来完成
如果你想拥有s
equals [[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 中有浮点值。
推荐阅读
- dart - 在 Flutter 中显示带省略号的段落
- wordpress - 在 woocommerce 中添加比较价格
- theorem-proving - 如何证明 Mizar(数学定理证明语言)中有一个等于 1 的自然数?
- java - 如何将 comp3 文件解压缩为可读格式?
- python - 如何摆脱 Pycharm 控制台中的省略号并使用 Quandl 显示信息?
- haskell - 读取语句列表并以单个表达式结尾,when 语句可以是表达式
- debugging - PyCharm 在调试模式下说“无法显示帧变量”?(与 gevent 无关)
- python - 如何应用动态规划来计算图中的最短路径?
- google-cloud-platform - 在数据存储中创建/更新触发云功能
- python - 从一列中提取并复制以“Unit”开头的字符串到新列:Pandas