输入一个数据文件.txt并使用Python将特定数据输出到新的.txt文件中

2024-09-28 16:18:50 发布

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

我想输入或读取.txt文件的以下数据:

VIBRATION/SHOCK CALIBRATION DATA
DATE: 2/26/2012 
TIME: 0800
Time (ms)   Channel 1    Channel 2     Channel 3
0.0         -0.9         9.0           12.9
50.0        5.0          12            343  
100.0       56.7         120           0.8
150.0       90.0         0.9           12.0
200.0       32.9         12.4          34.0

然后输出到一个新的.txt文件,以便只写入时间和通道3列的数字:

^{pr2}$

Tags: 文件数据txtdatadatetime时间channel
3条回答

可以对行字符串调用split()以获取列:

t, ch1, ch2, ch3 = line.split()

返回的值将是字符串。如果需要数字,请使用float()转换它们:

^{pr2}$

作为一个完整的例子,考虑下面的代码。我添加了过多的评论来解释每一步都在做什么。在

# Open the input file read-only...
with open('infile.txt', 'r') as infile:
    # Skip the first 4 lines, and store them as "header" in case we need them...
    # It's important that we use "next" here and _not_ infile.readline().
    # readline and the file iteration methods ("for line in file") can't be mixed
    header = [next(infile) for dummy in range(4)]

    # Open the output file, overwriting whatever is there...
    with open('outfile.txt', 'w') as outfile:
        # Loop over the lines in the input file
        for line in infile:
            # Strip off leading and trailing whitespace (e.g "\n") and 
            # split on whitespace. This gives us a list of strings.
            columns = line.strip().split()
            # Write the 1st and 4th columns in each row as left-justified 
            # columns with a fixed-width of 8
            outfile.write('{:8}{:8}\n'.format(columns[0], columns[3]))

如果您使用的是旧版本的python并且希望避免with语句,可以这样写:

^{pr2}$

不过,养成使用with语句处理文件对象的习惯是个好主意。它们确保即使代码中有错误,文件句柄也会自动关闭。with语句是“上下文管理器”。对于许多需要“样板”清理和/或输入代码的事情,它们非常方便。在

我不是一个真正的python人,但是基于您上面的评论,一旦您读懂了数据,您应该能够在每一行使用str.split()来获得该行中列的值。在

此处提供文档:http://docs.python.org/release/3.1.3/library/stdtypes.html#string-methods

相关问题 更多 >