Bruce
Bruce

Reputation: 23

(Python) Program to read specific data from many output files

I recently ran a simulation that output temporal data in directories numbered 0, 0.1, 0.2, ... , 10.

Within each of these directories there is a text file called rigidMotion which contains a line I want to read.

The line looks like:

centreOfRotation (0.000 0.000 0.000) //

where the numbers vary of course.

I would then like only the numbers to be sent to a text file or a csv file so I can plot them.

Given that its the same line in each file I was trying to use linecache but I'm not sure how to set up the for loop to read each directory.

Upvotes: 0

Views: 48

Answers (2)

Gábor Nagy
Gábor Nagy

Reputation: 26

For the directory reading this worked for me the best in multiple directories:

import os

for subdir, dirs, files in os.walk("your root directory"):
    for file in files:
        print os.path.join(subdir, file)
        #processing the files

For the line processing i would use string trimming if only the numbers change in it.

trimmedString = originalString[a:-b] 

where 'a' is the last index what you want to cut from the beginning, and 'b' is for the ending, in your case:

a = the index of the opening bracket

b = index of the closing bracket

Upvotes: 1

Jieter
Jieter

Reputation: 4229

You can use glob to find files according to a pattern, which in your case might be something like */rigidMotion, then iterate over those files and collect the values, outputting them to a new file.

Upvotes: 2

Related Questions