gpt4 book ai didi

python - 输入数据文件.txt,使用Python将特定数据输出到新的.txt文件

转载 作者:行者123 更新时间:2023-11-30 23:45:30 25 4
gpt4 key购买 nike

我想输入或读取.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 文件,以便仅写入时间和 channel 3 列的数字:

0.0     12.9
50.0 343
100.0 0.8
150.0 12.0
200.0 34.0

最佳答案

作为一个完整的示例,请考虑类似下面的代码。我添加了过多的注释来解释每个步骤的作用。

# 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 语句,您可以这样写:

# Open the input file read-only...
infile = open('infile.txt', 'r')
# Open the output file, overwriting whatever is there...
outfile = open('outfile.txt', 'w')

# 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)]

# 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]))

# Close the file objects once we're through with them..
# Python would close these automatically when the process ends, but it's a good
# idea to get in the habit of explicitly closing them once you don't need them.
# Otherwise, when you start writing code for longer-running processes, you'll
# inadvertently leave lots of file handles laying around
infile.close()
outfile.close()

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

关于python - 输入数据文件.txt,使用Python将特定数据输出到新的.txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9486689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com