Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解析文本文件并查找特定字符串_Python_Parsing_Text - Fatal编程技术网

Python 解析文本文件并查找特定字符串

Python 解析文本文件并查找特定字符串,python,parsing,text,Python,Parsing,Text,我有一个包含EPA油井信息的文本文件,它们是按州编码的。我想把每个州分解成它自己的文本文件。以下是我正在使用的代码: from __future__ import print_function import os, sys import numpy as np print(os.getcwd()) lines = [] #lines from file with open('UCMR3_All.txt') as well_list: for line in well_list:

我有一个包含EPA油井信息的文本文件,它们是按州编码的。我想把每个州分解成它自己的文本文件。以下是我正在使用的代码:

from __future__  import print_function
import os, sys
import numpy as np


print(os.getcwd())

lines = [] #lines from file
with open('UCMR3_All.txt') as well_list:
    for line in well_list:
        if line == "AL":
            #what goes here?

well_list_output = open(os.path.join('..','well_list_output.txt'),'w')

for line in lines:
    well_list_output.write(line)

well_list_output.close()
基本上,我想获取一行包含“AL”的内容并将其输出到自己的文件中。我尝试使用
行。追加(行)
,但似乎没有帮助。我当然会接受有用的提示或指导来代替答案

with open('UCMR3_All.txt') as well_list:
    for line in well_list.read().split('\n':
        if "AL" in line:
            lines.append(line)
稍后,您可以将
var写入一个文件。

基本上,列表是一个文件对象。它不是字符串,当然也不是列表。如果要将文件内容读入字符串,只需使用
read()
方法。

读取文件后,可以使用
split('\n')


将其拆分为行 现在剩下的就是遍历该列表并将好的行保存到列表中。即使在两行中也可以完成此操作:

这叫做列表理解。你可以在线阅读更多。
现在,要将行列表打印到文件(不同的文件),您可以:


当然,这个问题在网站上出现了10次。对于文件1中的行:如果行中的'AL':文件2.写入(行)??您可以在一个
中打开两个文件,使用
语句从一个文件读取,然后写入另一个文件。类似于well\u列表中的行,可以避免读取整个文件内容。相反,它逐行读取文件。对于非常大的文件,这可能很重要。
with open('UCRM3_All.txt', 'r') as fileObj:
    lines[:] = [line for line in fileObj.read().split('\n') if "AL" in line]
for i in xrange(len(lines)):
    with open("f" + str(i) = ".txt", "w") as fileObj:
        fileObj.write(lines[i])