python - Code for coyping specific lines from multiple files to a single file (and removing part of the copied lines) -
first of all, new this. i've been reading on tutorials on past days, i've hit wall want achieve.
to give long version: have multiple files in directory, of contain information in lines (23-26). now, code have find , open files (naming pattern: *.tag
) , copy lines 23-26 new single file. (and add new line after each new entry...). optionally remove specific part each line not need:
-> before c12b2 (or similar) need removed.
thus far have managed copy lines single file new file, rest still eludes me: (no idea how formatting works here)
f = open('2.tag') n = open('output.txt', 'w') i, text in enumerate(f): if >= 23 , < 27: n.write(text) else: pass
could give me advice ? not need complete code answer, however, tutorials don't skip explanations seem hard come by.
without importing os
:
#!/usr/bin/env python3 import os # set directory, outfile , tag below dr = "/path/to/directory"; out = "/path/to/newfile"; tag = ".txt" f in [f f in os.listdir(dr) if f.endswith(".txt")]: open(out, "+a").write(("").join([l l in open(dr+"/"+f).readlines()[22:25]])+"\n")
what does
it describe, it:
- collects defined region of lines files (that is: of defined extension) in directory
- pastes sections new file, separated new line
explanation
[f f in os.listdir(dr) if f.endswith(".tag")]
lists files of specific extension in directory,
[l l in open(dr+"/"+f).readlines()[22:25]]
reads selected lines of file
open(out, "+a").write()
writes output file, creates if not exist.
how use
- copy script empty file, save
collect_lines.py
- set in head section directory files, path new file , extension
run command:
python3 /path/to/collect_lines.py
the verbose version, explanation
if "decompress" code above, happens:
#!/usr/bin/env python3 import os #--- set path directory, new file , tag below dr = "/path/to/directory"; out = "/path/to/newfile"; tag = ".txt" #--- files = os.listdir(dr) f in files: if f.endswith(tag): # read file list of lines content = open(dr+"/"+f).readlines() # first item in list = index 0, line 23 index 22 needed_lines = content[22:25] # convert list string, add new line string_topaste = ("").join(needed_lines)+"\n" # add lines new file, create file if necessary open(out, "+a").write(string_topaste)
Comments
Post a Comment