-4

I've got a text file with EPA well information and they are coded by state. I want to break out each state into its own text file. Here is the code I'm working with:

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()

Basically, I want to take a line that contains "AL" and output it to its own file. I've attempted to use lines.append(line) but that doesn't seem to help. I'll certainly accept helpful nudges or guidance in lieu of the answer!

1 Answers1

0
with open('UCMR3_All.txt') as well_list:
    for line in well_list.read().split('\n':
        if "AL" in line:
            lines.append(line)

Later you can just write the lines var into a file.

Basically, well_list is a file object. It's not a string and certainly not a list. If you want to read the file contents into a string, just use the read() method.

After reading the file, you can split it to lines using split('\n').

Now everything left is to iterate through that list and save the good lines to a list. This can be done even in 2 lines:

with open('UCRM3_All.txt', 'r') as fileObj:
    lines[:] = [line for line in fileObj.read().split('\n') if "AL" in line]

This is called List Comprehension. You can read more online.
Now for printing the lines list to files (different files) you can:

for i in xrange(len(lines)):
    with open("f" + str(i) = ".txt", "w") as fileObj:
        fileObj.write(lines[i])
Yotam Salmon
  • 2,400
  • 22
  • 36
  • Iterating like _for **line** in **well_list**_ may avoid reading whole file content. Instead it read file line-by-line. This may be important in case of very large files. – Dmitrii Bulashevich Jun 07 '16 at 13:34