counting number with 3 csvs python



我有3个csv,我想将一列更改为一个连续的数字,该数字取决于文件中的行数。对于exmaple,文件1有400行,文件2有240行,文件3有100行。因此为文件1添加的列将是从1到400的序号。因此为文件2添加的列将是从401到640的序号。因此为文件3添加的列将是从641到741的序号。

我写的是这个

file1 = str(path) + "file1"
file2 = str(path) + "file2"
file3 = str(path) + "file3"
files = [file1, file2, file3]

class File_Editor():
def line_len(self):
for k in range(0,2):
file_name = open(files[k] + ".csv")
numline = len(file_name.readlines())
print (numline)

我一直坚持通过记住之前文件上的行数来为每个文件创建运行编号。

谢谢Alot!

+++++编辑

@roganjosh谢谢,我使用了你的代码,其中running_number=1有点固定,我已经把它放在def中,两个文件都有相同的运行号。

最后一件事,我如何在第一行添加索引,例如"数字"然后从第2行运行running_number_in_csv。

感谢

看看您之前悬而未决的问题,共同的主题是理解如何在Python中使用函数的根本问题,但这些问题没有得到解决。我将尝试解开其中的一部分,以防止出现类似的问题。我假设你和我一样有科学背景,所以我会坚持下去。

您从不向函数传递参数,只传递self。相反,您尝试从函数中引用全局变量,但没有必要,而且这很令人困惑。例如,我可能有一个方程y = x^2 + 3x + 5,它既是一个数学函数,也可以是一个python函数。

def quadratic(value_of_x):
y = (value_of_x **2) + (3*value_of_x) + 5
return y
eg_1 = quadratic(5)
print (eg_1)
eg_2 = quadratic(3)
print (eg_2)
# But this will fail
#print (y)

y仅作为局部变量存在于Python函数中,一旦离开def / return块就会被销毁。在这种情况下,eg_1eg_2假设函数末尾的y的值,value_of_x假设我在函数调用中放在括号中的值(自变量/变量)。这就是函数的意义所在,它们可以反复使用。

我还可以向函数传递多个参数。

def new_quadratic(value_of_x, coefficient):
y = coefficient*(value_of_x **2) + (3*value_of_x) + 5
return y
eg_3 = new_quadratic(5, 2)
print (eg_3)

我不仅不能在函数范围之外获得y的值,而且函数除非被调用,否则什么都不做。这毫无作用;这相当于你在脑子里知道了公式,但从来没有用数字来计算它——你只是把它定义为你的脚本可以使用的东西。

starting_number = 5
def modify_starting_number(starting_number):
starting_number = starting_number * 2
return starting_number
print (starting_number)

而这正是你所期望的。你调用函数,即通过公式传递数字。

starting_number = 5
def modify_starting_num(starting_num):
starting_num = starting_num * 2
return starting_num
starting_number = modify_starting_num(starting_number) # Calling the function
print (starting_number)

别这么说了,继续问你的问题。

import csv
files = ['file_1', 'file_2']
def running_number_in_csv(filename_list):
""" running_number resets every time the function is called, but is 
remembered within the function itself"""
running_number = 1 
for individual_file in filename_list:
new_rows = [] # Make something to hold row + extra column
# Read contents of each row and append the running number to the list
with open(individual_file + '.csv', 'r') as infile:
reader = csv.reader(infile)
for row in reader:
row.append(running_number)
new_rows.append(row)
running_number += 1 # Increments every row, regardless of file name number
# Write the list containing the extra column for running number
with open(individual_file + '.csv', 'w') as outfile: # Might need 'wb' in Windows
writer = csv.writer(outfile)
writer.writerows(new_rows)
get_running_number = running_number_in_csv(files) # CALL THE FUNCTION :) 

@roganjosh我已经修复了我的代码。我知道文件的长度是多少,现在我需要添加一个带有运行数字的列,如:

文件11至400

文件2401至641

文件3

642至742

非常感谢!

最新更新