Введите файл данных .txt и выведите конкретные данные в новый файл .txt, используя Python

1

Я хотел бы ввести или прочитать следующие данные файла.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 файл так, чтобы для столбцов Time и Channel 3 были записаны только цифры:

0.0     12.9
50.0    343
100.0   0.8
150.0   12.0
200.0   34.0
  • 0
    Я использовал счетчик только для чтения ниже времени, а затем для вывода в файл, но не знаю команды для извлечения только канала 3.
Теги:

3 ответа

3

В качестве полного примера рассмотрим что-то вроде кода ниже. Я добавил чрезмерные комментарии, чтобы объяснить, что делает каждый шаг.

# 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 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 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 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 заявлениями являются "менеджеры контекста". Они очень удобны для многих вещей, которые в противном случае требовали бы "готовой" очистки и/или кода входа.

  • 1
    Я бы добавил, что вы должны использовать rb и wb (чтение и запись в двоичном формате, соответственно), поскольку у него будет меньше межплатформенных проблем, чем в режимах r и w по умолчанию.
  • 0
    Спасибо за ответ. Имеет гораздо больше смысла.
0

Вы можете вызвать split() в строке строки, чтобы получить столбцы:

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

Возвращаемые значения будут строками. Если вы хотите числа, используйте float() для их преобразования:

t_f = float(t)
ch3_f = float(ch3)
0

Я на самом деле не парень-питон, но основываясь на вашем комментарии выше, как только вы прочитали данные, вы сможете использовать str.split() в каждой строке, чтобы получить значения столбцов в этой строке.

Документация здесь: http://docs.python.org/release/3.1.3/library/stdtypes.html#string-methods

Ещё вопросы

Сообщество Overcoder
Наверх
Меню