搜索、查找、打印、重命名PythonV2.7.5 String Ex

2024-06-16 11:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在StackOverflow上的第一篇帖子,如果太含糊,我深表歉意。 基本上,我有很多从程序输出的文件,我正在尝试自动收集所有数据的过程。你知道吗

我只需要以打印格式返回字符串的值。我已经设法做到了。但是,我还想在新打印的文件上创建一列,告诉我字符串来自哪个文件。你知道吗

我只用了6个小时。。。所以任何帮助都将非常感谢!你知道吗

文件内容的片段:

  GROWTH DIRECTION =         0  0  1
  SLICE SHIFT  5 =              0.00 ANGSTROMS
  LATTICE ENERGY =            -21.40 KCAL/MOL
  SLICE ENERGY =              -21.40 KCAL/MOL
  ATTACHMENT ENERGY =           0.00 KCAL/MOL
  SURFACE ENERGY =              0.00
  -------------------------------------------

这是我到目前为止的情况。你知道吗

# This script is to be used to pull out lines from strings. 
import re # Standard Regular expression module


lattE = open("TestFile.txt", "r") # opens the assigned file
lattEW = open("Lattice_Energies2.txt", "w") # Writes a new document to include all the lines that use LATTICE


for line in lattE: # looks through every line in the file 
    if re.match("(.*)(L)ATTICE(.*)", line): #searches the lines for LATTICE 
        print >>lattEW, line,  # Prints the lines 

电流输出:

  LATTICE ENERGY =            -21.40 KCAL/MOL
  LATTICE ENERGY =            -21.40 KCAL/MOL

Tags: 文件theto字符串retxtlineslice
3条回答

所以我进一步搜索了一下,发现这个非常有用的帖子[https://askubuntu.com/questions/352198/reading-all-files-from-a-directory][1]

试图把它和我现有的代码结合起来。。。它似乎没有打印到输出文件:|

import sys 
import glob
import errno
import re

path = '\*.sum' 
files = glob.glob(path)
lattEW = open("Lattice_En.txt", "a")
for name in files: # 'file' is a builtin type, 'name' is a less-ambiguous variable name.
    try:
        with open(name) as f: # No need to specify 'r': this is the default.
            sys.stdout.write(f.read())
        for line in name: # looks through every line in the file
                if re.match("(.*)(L)ATTICE(.*)", line): #searches the lines for LATTICE
                    print >>lattEW, name, line, 
    except IOError as exc:
        if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
            raise # Propagate other kinds of IOError 

替代方法。。。这确实奏效了。谢谢@Gabor Fekete。你知道吗

import fnmatch #Imports the synx for itteratively searching through Files 
import os 
import re #regex Expressions 
for file in os.listdir('/.'): #Goes through Files in Directory 
    if fnmatch.fnmatch(file, '*.sum'): # Selects files with .sum extension 
        lattE = open(file,"r")  #opens said files 
        lattEW = open("Latt_En.txt", "a") #Amends Summary file
        for line in lattE: # Goes through file 
            if re.match("(.*)(L)ATTICE(.*)", line): #Searches for term LATTICE
                print >>lattEW, lattE.name, line, #Prints to LattEW file , name and line 

您可以使用file对象的name属性。你知道吗

for line in lattE:
    if re.match("text", line):
        print lattE.name, line,

相关问题 更多 >