使用字符串行从文件中读取数值
Read numerical values from a file with lines of strings
我有一个包含 N 行的 .txt 文件。我想读取第 8 行和第 16 行,它们看起来像这样:
2016-04-01 04:27:30.6216 (2283721) (more text)
2016-04-01 04:59:20.3635 (2283721) (more text)
如何恢复值 04:59:20.3635 和 04:27:30.6216 并减去它们?我尝试使用
打开和读取文件
txt = open(filename)
for line in txt:
print line
但我不知道如何将每一行存储在一个变量中,然后访问我想要到达的行的特定部分。我已经尝试了一些东西,但我想知道哪种方法是处理这个问题的最有效方法。非常感谢!!
您可以制作一个字符串数组,然后让文件在 while 循环中将每一行打印到数组中。 while 循环检查您读入数组的量或何时停止读取文件。之后,只需简单地使用其他方法搜索特定行或数组索引即可找到您需要的内容。根据手头的任务,还有很多其他方法。
python 擅长操作字符串,所以在你的情况下
刚刚
timestamps =[]
for line in fh:
timestamps.append(line. split()[1])
print timestamps, timestamps[0]
您甚至可以通过使用库中的日期时间或时间增量相关构建来提取/计算时间增量,但首先,正如其他人评论的那样,您应该阅读本教程,相信我,如果您认为它很短且值得一读前几天你偶尔会掌握一些道理——你需要知道 python 通常可以做什么
以下是我的做法。希望对您有所帮助:
import re
from datetime import datetime
def get_date_time (t):
"""
t: date time string;
parse date time string, and return datetime
"""
time_string = re.findall('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{4}', t)[0]
return datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S.%f')
if __name__ == '__main__':
with open('input.txt') as f:
src = f.read().split('\n') # split into lines
print get_date_time(src[7]) - get_date_time(src[5]) # calculate difference
输出:
0:31:49.741900
我有一个包含 N 行的 .txt 文件。我想读取第 8 行和第 16 行,它们看起来像这样:
2016-04-01 04:27:30.6216 (2283721) (more text)
2016-04-01 04:59:20.3635 (2283721) (more text)
如何恢复值 04:59:20.3635 和 04:27:30.6216 并减去它们?我尝试使用
打开和读取文件txt = open(filename)
for line in txt:
print line
但我不知道如何将每一行存储在一个变量中,然后访问我想要到达的行的特定部分。我已经尝试了一些东西,但我想知道哪种方法是处理这个问题的最有效方法。非常感谢!!
您可以制作一个字符串数组,然后让文件在 while 循环中将每一行打印到数组中。 while 循环检查您读入数组的量或何时停止读取文件。之后,只需简单地使用其他方法搜索特定行或数组索引即可找到您需要的内容。根据手头的任务,还有很多其他方法。
python 擅长操作字符串,所以在你的情况下 刚刚
timestamps =[]
for line in fh:
timestamps.append(line. split()[1])
print timestamps, timestamps[0]
您甚至可以通过使用库中的日期时间或时间增量相关构建来提取/计算时间增量,但首先,正如其他人评论的那样,您应该阅读本教程,相信我,如果您认为它很短且值得一读前几天你偶尔会掌握一些道理——你需要知道 python 通常可以做什么
以下是我的做法。希望对您有所帮助:
import re
from datetime import datetime
def get_date_time (t):
"""
t: date time string;
parse date time string, and return datetime
"""
time_string = re.findall('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{4}', t)[0]
return datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S.%f')
if __name__ == '__main__':
with open('input.txt') as f:
src = f.read().split('\n') # split into lines
print get_date_time(src[7]) - get_date_time(src[5]) # calculate difference
输出:
0:31:49.741900