Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取了一个包含有关共享信息的.dat文件。必须创建计算平均市场价格的模块_Python_List_File - Fatal编程技术网

Python 获取了一个包含有关共享信息的.dat文件。必须创建计算平均市场价格的模块

Python 获取了一个包含有关共享信息的.dat文件。必须创建计算平均市场价格的模块,python,list,file,Python,List,File,好的,我有以下格式的4.dat文件: Purchase Date Purchase Price Shares Symbol 25 Jan 2014 63.70 40 FB 25 Jan 2014 64.04 40 FB 25 Jan 2014 63.97 175 FB 25 Jan 2014

好的,我有以下格式的4.dat文件:

Purchase Date     Purchase Price     Shares     Symbol

25 Jan 2014           63.70            40         FB

25 Jan 2014           64.04            40         FB

25 Jan 2014           63.97            175        FB

25 Jan 2014           63.72            80         FB
需要注意的重要一点是,每一列(购买日期、购买价格、股份、符号)都由制表符(\t)分隔。此外,“2014年1月25日”仅用逗号分隔。然后是股票价格的制表符分离,因为它在下一列中,依此类推。显然还有空行

我必须创建一个模块,读取我将放入其中的文件(该文件是4个文件的一个示例,格式相同,但价格和股数不同),并计算该股票的平均市场价格(价格x股数/总股数)

因此,基本上问题是如何将python指向我想要的信息:

到目前为止,我唯一想到的是

def averagePricePerShare(x):

   """Calculates average market price"""

    sharesdata_file=(open(x,"r")) #opens file
    sharesdata_str=sharesdata_file.read() #reads contents of file into a string
    marketavgprice=(price*shares)/totalshares
当然,在最后一行中,这些变量还没有定义,因为我不知道如何找到它们。当然,我必须以某种方式使用.find()函数,我真的不知道。任何帮助都将不胜感激。这是我最后的选择,在论坛上寻求帮助之前,我一直试图自己想出一些办法。也许我只是因为在过去的8个小时里一直在做这项任务而被卡住了(相当大的任务,这是最后的部分之一)

编辑:我的错。看起来开始点应该是使用.split()函数拆分所有有空行的文本,然后再拆分有制表符的文本。拆分('\n')和.split('\t')或其他内容。或者去掉空行,然后分别处理每一行,并在.split('\t')处拆分行,这样每一行的购买价格为.split('\t')[1],股票价格为.split('\t')[2]?如果是这样的话我该怎么做

编辑2:我必须在不使用内置函数的情况下执行此操作。手动。我发现了如何:

first_useful_line=sharesdata_str.split('\n')[2]
等等。现在我想我会像这样把这行分成几列

firstlineprice=first_useful_line.split('\t')[1]

想法?

使用
csv
模块读取数据,指定
分隔符=“\t”

import csv

with open("myfile.dat", "rb") as inf:                # if Python 2.x
# with open("myfile.dat", "r", newline="") as inf:     # if Python 3.x
    incsv = csv.reader(inf, delimiter="\t")

    # skip header row
    next(incsv, None)   

    # read data
    for row in incsv:
        # now do something with row!