在python中读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4065594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:04:40  来源:igfitidea点击:

reading a file in python

pythonstringcsv

提问by user458858

I am new to python been using it for graphics but never done it for other problems. My question is how to read this file which is tab or space delimited and has headers in python, i know how to do comma delimted file but not done this on?

我是 python 的新手,一直将它用于图形,但从未为其他问题做过。我的问题是如何读取这个由制表符或空格分隔并在 python 中有标题的文件,我知道如何做逗号分隔的文件但没有这样做?

ID  YR  MO  DA  YrM  MoM  DaM  
100  2010  2  20  2010  8  2010  30  
110  2010  4  30  2010  9  2010 12     
112  2010  8  20  2010  10  2010  20  

Also is there a way to find the difference of number of days between two dates.

还有一种方法可以找到两个日期之间的天数差异。

采纳答案by MAK

For simple tasks, you can just use the str.split()method. split()takes the delimiter as its parameter, but splits on whitespace if none is given.

对于简单的任务,您可以只使用该str.split()方法。split()将分隔符作为其参数,但如果没有给出,则在空格上拆分。

>>> lin="a b c d"
>>> lin.split()
['a', 'b', 'c', 'd']

回答by pyfunc

Does the same technique for csv modules does not work?

csv 模块的相同技术是否不起作用?

import csv
reader = csv.reader(open("filename"), delimiter="\t")

Delimiter can be "\s" or "\t".

分隔符可以是“\s”或“\t”。

You can also use DictReader this way:

你也可以这样使用 DictReader:

f = open(filename, '')
try:
    reader = csv.DictReader(f)
    for row in reader:
        print row
finally:
    f.close()

you can also use brute force technique

你也可以使用蛮力技术

for line in open(filename):
    listWords = line.split("\t")

Split function:

拆分功能:

>>> t = 'ID YR MO DA YrM MoM DaM'
>>> t.split(" ")
['ID', 'YR', 'MO', 'DA', 'YrM', 'MoM', 'DaM']

For calculating no of days, use datetime module : http://docs.python.org/library/datetime.html

要计算天数,请使用 datetime 模块:http: //docs.python.org/library/datetime.html

>>> import datetime
>>> k = datetime.date(2010, 05, 26) - datetime.date(2010, 02, 10)
>>> k.days
105
>>>