readline跳过for循环的第一行

readline跳过for循环的第一行

本文介绍了readline跳过for循环的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于循环来说,我遇到了一个跳过第一行的问题。我知道为什么,但我不知道如何解决这个问题。而当我把它改成一个而循环,或者事实上,它给了我一个错误:

 第29行,在< module> 
worksheet.write(row,col,float(b))
ValueError:无法将字符串转换为float:

代码是:

$ p $ import xlsxwriter
import tkinter

file_list = []
x = 1
while x file_list.append('AuF7_PATP10_5M_MgF2_20μl_1s_S'+ str(x)+'_calibrated.txt')
x + = 1
workbook = xlsxwriter.Workbook(file_list [0] +'。xlsx')
worksheet = workbook.add_worksheet()
$ b $ row = 1
$ col = 0
f = open(file_list [0],'r')
for line in f:
a = f.readline()
b = a [0:(a .rfind(\ t))]
c = a [(a.rfind(\ t)): - 1]
worksheet.write(row,col,float(b) )
worksheet.write(row,col + 1,float(c))
row + = 1


循环访问文件 读取行。你不需要也不应该再次调用 f.readline()。你已经在行行中,所以就使用它。



此外,你似乎有制表符分隔数据;考虑使用 csv 模块拆分你的行;它也可以将你的数据转换为浮动:
$ b $ pre $ reader = csv.reader(f,delimiter ='\ t' (b,c)在枚举(reader,1)中:
worksheet.write(row,0,b)
worksheet.write(row, ,1,c)

以上使用 enumerate()给每个数据行一个计数器。 csv.QUOTE_NONNUMERIC 引用选项会导致输入文件中不包含引号的内容被自动转换为 float 对象。

I've got a problem with a for loop that skips the first line. I know why but I don't know how to fix it. And when I change it to a while loop, or in a matter of fact in to anything, it gives me an error:

line 29, in <module>
    worksheet.write(row, col, float(b))
ValueError: could not convert string to float:

The code is:

import xlsxwriter
import tkinter

file_list = []
x = 1
while x <= 30:
    file_list.append('AuF7_PATP 10_5M_MgF2_20µl_1s_S' + str(x) + '_calibrated.txt')
    x+=1
workbook = xlsxwriter.Workbook(file_list[0]+'.xlsx')
worksheet = workbook.add_worksheet()

row = 1
col = 0
f = open(file_list[0], 'r')
for line in f:
    a = f.readline()
    b = a[0:(a.rfind("\t"))]
    c = a[(a.rfind("\t")):-1]
    worksheet.write(row, col, float(b))
    worksheet.write(row, col + 1, float(c))
    row += 1
解决方案

Looping over the file already reads lines. You don't need nor should you call f.readline() again. You already have the line in line, so just use that.

Moreover, you appear to have tab-separated data; consider using the csv module to split your rows; it can also convert your data to floats for you:

reader = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONNUMERIC)
for row, (b, c) in enumerate(reader, 1):
    worksheet.write(row, 0, b)
    worksheet.write(row, 1, c)

The above uses enumerate() to give you a counter per data row as well. The csv.QUOTE_NONNUMERIC quoting option causes anything not in quotes in your input file to be auto-converted to float objects.

这篇关于readline跳过for循环的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:39