从文本文件python

时间:2016-06-30 04:06:28

标签: python sum text-files

我想知道如何在python中查找文本文件中列的总数。

我的档案:

123  Hammer  20  36
124  Knife   10  10
125  Rod     90  20

我想在文本文件中添加第4列。这是以36开头的列。该函数应返回66的列的总和。

我还没有任何代码,因为我仍然坚持这个问题并想办法解决它。

我在某些地方出错,我认为这是由于我的代码。我需要帮助。

# Creating class Hardware to store the linked list data in to the class, Properties like get and set
class Hardware:
    def __init__(self,barcode,description,price,quantity): # initating data
        self.barcode=barcode
        self.description=description
        self.price=price
        self.quantity=quantity
        self.next=None

    def getData(self):#function to get data
        return self.barcode,self.description,self.price,self.quantity

    def getNext(self):#function to get the next data
        return self.next

    def setData(self,newBarcode,newDescription,newPrice,newQuantity):#function to set the data
        self.barcode=newBarcode
        self.description=newDescription
        self.price=newPrice
        self.quantity=newQuantity

    def setNext(self,newNext):#function to set the next data
        self.next=newNext

# LinkedList class for manipulation of data that is add, display and update
class LinkedListHardware:
    def __init__(self): # initating data
        self.head=None

    def isEmpty(self): #checks if the data is empty
        return self.head==None

    def ReadFile(self): # Reads a text file called Hardware
        Hardwarefile=open('Hardware.txt','r')
        return Hardwarefile.read()

    def add(self,itemBarcode,itemDescription,itemPrice,itemQuantity): #Adds data to the linked list and also writes to the file
        temp=Hardware(itemBarcode,itemDescription,itemPrice,itemQuantity)
        temp.setNext(self.head)
        self.head=temp
        HardwareItems=(itemBarcode,itemDescription,itemPrice,itemQuantity)
        Hardwarefile=open('Hardware.txt','a+')
        Hardwarefile.write('\n')
        for items in HardwareItems:
            Hardwarefile.write(str(items)+'\t')
        return "Added Successfully"
        Hardwarefile.close()


    def display(self,itemBarcode): # Displays a line based on the Barcode the user enters
        current=self.head
        with open('Hardware.txt','r') as f:
            found=False
            for line in f:
                lines=line.split()
                if itemBarcode in lines:
                    found=True
                    return line
            if not found:
                 return "No such Barcode"
            f.close()        

    def update(self,itemBarcode,itemDescription,itemPrice,itemQuantity): #update data of hardware item
            current=self.head
            with open('Hardware.txt','r+') as f:
                found=False
                for lines in f:
                    line=lines.split()
                    if itemBarcode not in line:
                        array=[]
                        array.append(line)
                        st=[x[0]+'\t'+x[1]+'\t'+x[2]+'\t'+x[3] for x in array]
                        st=''.join(st)

                        with open('Hardwareupdate.txt','a+') as outfile:
                            outfile.write('\n'+str(st))
                            found=True
                        HardwareItems=(itemBarcode,itemDescription,itemPrice,itemQuantity)
                        Hardwarefile=open('Hardwareupdate.txt','a+')
                        Hardwarefile.write('\n')
                        for items in HardwareItems:

                            Hardwarefile.write(str(items)+'\t')

                return "Added Successfully"


            if not found:
                    return "No such Transaction"



# Creating class Transaction to store the linked list data in to the class, Properties like get and set
class Transaction:
    def __init__(self,invoiceNumber,Barcode,totalPrice,Quantity): # initating data
        self.invoiceNumber=invoiceNumber
        self.Barcode=Barcode
        self.totalPrice=totalPrice
        self.Quantity=Quantity

        self.next=None

    def getData(self): #function to get data
        return self.invoiceNumber,self.Barcode,self.totalPrice,self.Quantity

    def getNext(self): #function to get the next data
        return self.next

    def setData(self,newinvoiceNumber,newBarcode,newtotalPrice,newQuantity): #function to set the data
        self.invoiceNumber=newinvoiceNumber
        self.Barcode=newBarcode
        self.totalPrice=newtotalPrice
        self.Quantity=newQuantity


    def setNext(self,newNext): #function to set the next data
        self.next=newNext

# LinkedList class for manipulation of data that is add, search, update and delete
class LinkedListTransaction:

    # initating data
    def __init__(self):
        self.head=None

    #checks if the data is empty
    def isEmpty(self):
        return self.head==None

    #Adds data to the linked list and also writes to the file
    def add(self,iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice):
        temp=Transaction(iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice)
        temp.setNext(self.head)
        self.head=temp
        TransactionItems=(iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice)
        Transactionfile=open('Transaction.txt','a+')
        Transactionfile.write('\n')
        for items in TransactionItems:
            if iteminvoiceNumber != ' ':
                Transactionfile.write(str(items)+'\t')
        return "Added Successfully"

    # Displays the record of data by receving the item invoice number
    def display(self,iteminvoiceNumber):
            current=self.head
            with open('Transaction.txt','r') as f:
                found=False
                for line in f:
                    lines=line.split()
                    if iteminvoiceNumber in lines:
                        found=True
                        return line
                if not found:
                     return "No such Transaction"

    # Removes sepcific data from the file (rewrites data that does not contain the data which user entered and writes to another file)
    def remove(self,iteminvoiceNumber):
        current=self.head
        with open('Transaction.txt','r') as f:
            found=False
            for lines in f:
                line=lines.split()

                if iteminvoiceNumber not in line:
                    array=[]
                    array.append(line)
                    st=[x[0]+'\t'+x[1]+'\t'+x[2]+'\t'+x[3] for x in array]
                    st=''.join(st)
                    with open('Transactionlatest.txt','a+') as outfile:
                        outfile.write('\n'+str(st))
                        found=True

            if not found:
                    return "No such Transaction"

    # Updates Data from the text file. Copies data to new file and then update whatever user enters
    def update(self,iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice):
            current=self.head
            with open('Transaction.txt','r+') as f:
                found=False
                for lines in f:
                    line=lines.split()
                    if iteminvoiceNumber not in line:
                        array=[]
                        array.append(line)
                        st=[x[0]+'\t'+x[1]+'\t'+x[2]+'\t'+x[3] for x in array]
                        st=''.join(st)

                        with open('Transactionupdate.txt','a+') as outfile:
                            outfile.write('\n'+str(st))
                            found=True
                        TransactionItems=(iteminvoiceNumber,itemBarcode,itemQuantity,itemtotalPrice)
                        Transactionfile=open('Transactionupdate.txt','a+')
                        Transactionfile.write('\n')
                        for items in TransactionItems:

                            Transactionfile.write(str(items)+'\t')

                return "Added Successfully"


            if not found:
                    return "No such Transaction"


    def TotalSales(self):
        mysum=0
        with open('Transaction.txt','r') as f:
            for line in f:
                mysum+=int(line.split()[3])
            return mysum





HardwareList=LinkedListHardware()

TransactionList=LinkedListTransaction()
print(TransactionList.TotalSales())
print(TransactionList.remove(input()))
'''
print("Hardware Shop\n")
print("[1]Update hardware item quantity in hand or price per unit\n")
print("[2]Add hardware item\n")
print("[3]Display hardware item\n")
print("[4]Add Sales Transaction\n")
print("[5]Remove Sales Transaction\n")
print("[6]Edit Sales Transaction\n")
print("[7]All Sales Transaction\n")        

MainInput=input("Enter Selection: ")

HardwareList=LinkedListHardware()

TransactionList=LinkedListTransaction()


if MainInput=='1':
    print("\nUpdate hardware item quantity in hand or price per unit")
    print(HardwareList.update(input("Enter Barcode: "),input("Enter Description: "),input("Enter Price: "),input("Enter Quantity: ")))
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")


if MainInput=='2':
    print("\nAdd hardware item")
    print(HardwareList.add(input("Enter Barcode: "),input("Enter Description: "),input("Enter Price: "),input("Enter Quantity: ")))
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")

if MainInput=='3':
    print("\nDisplay hardware item")
    print(HardwareList.display(input("Enter Barcode: ")))
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")

if MainInput=='4':
    print("\nAdd Sales Transaction")
    print(TransactionList.add(input("Enter Invoice Number: "),input("Enter Hardware Barcode: "),input("Enter Quantity: "),input("Enter Total Price: ")))
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")

if MainInput=='5':
    print("\nRemove Sales Transaction")
    print(TransactionList.remove(input("Enter Invoice Number: ")))
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")

if MainInput=='6':
    print("\nEdit Sales Transaction")
    print(TransactionList.update(input("Enter Invoice Number: "),input("Enter Hardware Barcode: "),input("Enter Quantity: "),input("Enter Total Price: ")))
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")

if MainInput=='7':
    print("\nAll Sales Transaction")
    print(TransactionList.TotalSales())
    SubInput=int(input("Enter 0 to exit and 1 to continue "))
    if SubInput==0:
        quit()
    if SubInput==1:
        print("Hardware Shop\n")
        print("[1]Update hardware item quantity in hand or price per unit\n")
        print("[2]Add hardware item\n")
        print("[3]Display hardware item\n")
        print("[4]Add Sales Transaction\n")
        print("[5]Remove Sales Transaction\n")
        print("[6]Edit Sales Transaction\n")
        print("[7]All Sales Transaction\n")        

        MainInput=input("Enter Selection: ")



'''

错误是接收

mysum+=int(line.split()[3])
IndexError: list index out of range

3 个答案:

答案 0 :(得分:1)

你可以使用熊猫:

http://pandas.pydata.org/pandas-docs/stable/io.html

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html

import pandas as pd
df = pd.read_csv('myfilename.csv')
df[4] = df[3].sum(axis=0)

答案 1 :(得分:0)

这应该有效:

mysum = 0
with open('myfilename','r') as f:
    for line in f:
        mysum += int(line.split()[3])

line.split()会将"123 Hammer 20 36"变为["123", "Hammer", "20", "36"]。我们使用索引36获取第四个值[3]。这仍然是一个字符串,可以使用int或使用float的十进制(浮点)数字转换为整数。

编辑:

检查空行在for循环中添加条件if line:。在您的特定情况下,您可能会执行以下操作:

for line in f:
    words = line.split()
    if len(words)>3:
        mysum += int(words[3])

答案 2 :(得分:0)

这是打开文件的python,将每一行映射到最后的整数,然后对整数求和:

首先打开文件:

with open("my_file.txt") as f:
    # .readlines() method gives you a list of the lines in the file.
    lines = f.readlines()

接下来,我们必须编写一个函数,将任何给定行的最后一列作为整数返回。

def extract_last_int(line):
    return int(line.split()[-1])

# apply 'extract_last_int' to each line, and then sum the results.
print sum(map(extract_last_int, lines))
  • .split()方法默认情况下会分割为空格, 为您提供此行中每列的列表。

  • [-1]告诉python获取列表的最后一个元素。

  • map获取一个函数和一个列表,并为列表中的每个项调用一次函数。 map的返回值是每个调用的结果列表。在这种情况下,map的返回值是文件最后一列中的整数列表。

  • 最后,sum将所有这些整数添加到一起。

就是这样!

如果你很好奇,你可以用awk在一行中做同样的事情:

awk '{i+=$NF} END {print i}' my_file.txt