在 python 中加载和格式化文件

Load and formatting file in python

我有一个 n 行的文件,我想加载 python,格式是这样的

06:38:34 16.09.2017,  739648.4118,6077976.8575, 54.791616, 12.727939
06:38:35 16.09.2017,  739647.0628,6077975.6925, 54.791606, 12.727917

我希望它是这样的:

06 38 34 16 09 2017 739648.4118 6077976.8575  54.791616  12.727939
06 38 35 16 09 2017 739647.0628 6077975.6925  54.791606  12.727917

所以它变成了一个大小为(n,10)的数组。 我试过了

f=open('filename')
x.read()
f.close()

则x是一个字符串,大小为(1),所有数据都在一个元素中。我知道有一个名为 split 的命令,但我无法让它正常工作。有什么帮助吗?

怎么样:

with open('filename','r') as f:
    out = []
    a = f.read().replace(':',' ').replace(',','').split('\n')
    for i in a:
       out.append(i.split(' '))
    print(out[0:-1])

[0:-1] 删除最后一个空元素

我总是喜欢使用管道方法来处理文件,这样如果您的输入变得非常大,您就可以使用并发。无论如何,如果您使用 ipython,您可以使用 %timeit 轻松检查性能,但我会这样做:

processed = ""

def replace_char(line, char, replacement):
    return line.replace(char, replacement)

with open('SOME_PATH') as fh:
    processed += replace_char(replace_char(fh.read(), ":", " "), ",", "")

print(processed)

# OUTPUT
# 06 38 34 16.09.2017  739648.41186077976.8575 54.791616 12.727939
# 06 38 35 16.09.2017  739647.06286077975.6925 54.791606 12.727917

使用这种方法,如果您想更改处理文件的方式,您所要做的就是更改 replace_char,或者如果您愿意,可以编写一些其他函数。如果您需要并发,那么您可以使用 multiprocessingasyncio 包。

这应该可以使用 pandas

实现您想实现的目标
import pandas as pd

df = pd.read_csv('<your file>', header=None, names=['DateTime', 'Num1', 'Num2', 'Num3', 'Num4'])
df['DateTime'] = pd.to_datetime(df['DateTime'])

# Split datetime object in to seperate columns as desired output format
df['hour'] = df['DateTime'].dt.hour
df['minute'] = df['DateTime'].dt.minute
df['second'] = df['DateTime'].dt.second
df['day'] = df['DateTime'].dt.day
df['month'] = df['DateTime'].dt.month
df['year'] = df['DateTime'].dt.year

# Drop the DateTime columns
df.drop('DateTime', inplace=True, axis=1)

# Switch the order of columns to desired order
df = df[['hour', 'minute', 'second', 'day', 'month', 'year', 'Num1', 'Num2', 'Num3', 'Num4']]

#export to file with ' ' as seperator
df.to_csv('output file.txt', sep=' ', index=False, header=None)