Python Forum
Select specific zone in .txt file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Select specific zone in .txt file
#1
Hello everyone !!

I have a very large number of .txt files that all have the same structure (only numerical values are different) and are all in the same folder :

Name = [102, 22]_[152, 32]_1_1_1
Mach = 0; Re = 2000000; T.U. = 1.0; T.L. = 1.0
Surface Finish = 0; Stall model = 0; Transition model = 1; Aspect Ratio = 0; ground effect = 0
?	Cl	Cd	Cm 0.25	T.U.	T.L.	S.U.	S.L.	L/D	A.C.	C.P.
[°]	[-]	[-]	[-]	[-]	[-]	[-]	[-]	[-]	[-]	[-]
0.0	-2.868	0.02003	1.113	1.521	1.772	1.523	1.963	-143.170	0.250	0.638
The only value I am interested in is Cl (-2.868 here).

Since all files have the same structure, that all Cl values are negative with the same number of digits, they are therefore always at the same location.

I'd like to browse all .txt file from my folder and extract the Cl value in each of them in order to write it in a new .txt file (in which at the end all Cl values will be written).

Is it possible and if yes how can I do it ?
Thanks in advance for your help,
Scientifix
Reply
#2
Hello and welcome to the forums!
What you want to achieve is certainly possible. You can do it in a few steps. First read the file. You can traverse the lines and find the line you want by a pattern. But if the value you want is always on 6th line, it's even easier, just read the 6th line. Then you can convert the string (line) to a list and get the 2nd element from it.

That is basically it. For all of the steps you can find ample resources online. If you get stuck, feel free to post the code (in Python code tags), errors in error tags if you get them, or actual vs desired result if it won't work as expected.
Reply
#3
Thank you very much for your answer !!
The second part of my question is still unsolved :
Do you know a way to browse files from a folder ?
Something like :

for file in folder:
        operations on file
Thank you very much !!
Reply
#4
I believe this answer on SO gives a way better presentation than I could, I hope it helps.
Reply
#5
In the past, I would have suggested glob, but now we have pathlib, which is fantastic. Here's an example:
from pathlib import Path

current_dir = Path(".")

# iterate over all objects in this folder
for obj in current_dir.iterdir():
    # skip sub-folders
    if obj.is_file():
        # open the file
        with open(obj) as f:
          # print the first line of the file
          for line in f:
              print(f"{obj} => {line}")
              break
Reply
#6
Thank you very much nilamo !!

When I run your script I have this error :

Error:
with open(obj) as f: TypeError: invalid file: WindowsPath(''Cl_selection.py'')
What's wrong ? Do I have to put my python script out side the folder ? But then it will browse the wrong foler...
Reply
#7
Make sure it only open .txt file and '.' you run in folder with files or specify a path.
Example make a couple of files and extract number:
from pathlib import Path
import re

current_dir = Path(".")
lst = []
for obj in current_dir.iterdir():
    if obj.is_file() and obj.suffix.endswith('.txt'):
        with open(obj) as f:
            lst.append(re.search(r'\d\.\d\s(-\d.\d+)', f.read()).group(1))
Output:
>>> lst ['-2.868', '-9.999'] >>> [float(i) for i in lst] [-2.868, -9.999]
Reply
#8
Corrected : with obj.open() as f

small mistake on indexes but seems to work

from pathlib import Path
 
current_dir = Path(".")

file = open("Configurations_and_Cl.txt","w")
 
# iterate over all objects in this folder
for obj in current_dir.iterdir():
    # skip sub-folders
    if obj.is_file() and obj.suffix.endswith(''):
        # open the file (my files are in no format)
        with obj.open() as f: 
        
            #read lines of the .txt file
            lines = f.readlines()
            # write name and Cl in file
            file.write(str(lines[0])[7:] + ' ')
            file.write(str(lines[5])[4:10] + '\n')
        
        
file.close() 
Reply
#9
(Apr-28-2018, 02:50 PM)Scientifix Wrote: and obj.suffix.endswith(''):
Why add a condition that'll always be true?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Extracting specific file from an archive tester_V 4 527 Jan-29-2024, 06:41 PM
Last Post: tester_V
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,060 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Reading Specific Rows In a CSV File finndude 3 1,004 Dec-13-2022, 03:19 PM
Last Post: finndude
  How to extract specific data from .SRC (note pad file) Shinny_Shin 2 1,285 Jul-27-2022, 12:31 PM
Last Post: Larz60+
  select files such as text file RolanRoll 2 1,182 Jun-25-2022, 08:07 PM
Last Post: RolanRoll
  Extracting Specific Lines from text file based on content. jokerfmj 8 3,056 Mar-28-2022, 03:38 PM
Last Post: snippsat
  [Solved] Trying to read specific lines from a file Laplace12 7 3,570 Jun-21-2021, 11:15 AM
Last Post: Laplace12
  Extract specific sentences from text file Bubly 3 3,424 May-31-2021, 06:55 PM
Last Post: Larz60+
  Subprocesses not opening File Select Dialog teut 2 2,424 Feb-22-2021, 08:07 PM
Last Post: teut
  Find specific file in an archive tester_V 8 3,507 Feb-13-2021, 06:13 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020