如何读取这种特殊的文件格式?

2024-05-29 04:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

csv文件中包含以下文本:

b'DataMart\n\nDate/Time Generated,11/7/16 8:54 PM\nReport Time Zone,America/New_York\nAccount ID,8967\nDate Range,10/8/16 - 11/6/16\n\nReport Fields\nSite (DCM),Creative\nGlobest.com,2016-08_CB_018_1040x320_Globe St_16_PropertyFilter\nGlobest.com,2016-08_CB_018_1040x320_Globe St_16_PropertyFilter'

基本上,这个文件中有多个新行字符,而不是一个大字符串,因此您可以按如下方式描绘相同的文本

DataMart
Date/Time Generated,11/7/16 8:54 PM
Report Time Zone,America/New_York
Account ID,8967
Date Range,10/8/16 - 11/6/16
Report Fields
Site (DCM),Creative
Globest.com,2016-08_CB_018_1040x320_Globe St_16_PropertyFilter
Globest.com,2016-08_CB_018_1040x320_Globe St_16_PropertyFilter

我需要抓取最后两行,基本上就是数据。我试过做for循环:

with open('file.csv','r') as f:
    for line in f:
        print(line)

而是用\n再次打印整行。你知道吗


Tags: 文件csv文本comzonetimegeneratedst
2条回答

只需读取文件并获取最后两行:

my_file = file("/path/to/file").read()
print(my_file.splitlines()[-2:])

[-2:]被称为切片:它创建一个切片,从第二个到最后一个元素开始,一直到最后一个元素。你知道吗

好吧,经过一段时间的努力,我发现我需要将文件的解码从二进制改为utf-8,然后我就可以应用split函数了。问题是分割函数不适用于二进制文件。你知道吗

这就是我现在的实际代码:

    with open('BinaryFile.csv','rb') as f1:
        data=f1.read()
        text=data.decode('utf-8')
        with open('TextFile.csv', 'w') as f2:
            f2.write(text)

    with open('TextFile.csv','r') as f3:
        for line in f3:
            print(line.split('\\n')[9:])

谢谢你们的帮助

相关问题 更多 >

    热门问题