tags:

views:

101

answers:

4

Hey I need to split a large file in python into smaller files that contain only specific lines. How do I do this?

A: 

How big and does it need to be done in python? If this is on unix, would split/csplit/grep suffice?

eruciform
This probably could have been posted as a comment...
Wayne Werner
+1  A: 

Do you mean breaking it down into subsections? Like if I had a file with chapter 1, chapter 2, and chapter 3, you want it to be broken down into separate files for each chapter?


The way I've done this is similar to Wilduck's response, but closes the input file as soon as it reads in the data and keeps all the lines read in.

data_file = open('large_file_name', 'r')
lines = data_file.readlines()
data_file.close()

outputFile = open('output_file_one', 'w')
for line in lines:
    if 'SomeName' in line:
        outputFile.write(line)

outputFile.close()

If you wanted to have more than one output file you could either add more loops or open more than one outputFile at a time.

I'd recommend using Wilducks response, however, as it uses less space and will take less time with larger files since the file is read only once.

thegrinner
I have a large file that I want to extract certain lines from. I need to search through the file and find the line that has Charlie, Mark, and Steve in it and omit the lines the belong to all the other people.
novak
This isn't an answer. It should probably be in a comment.
Wilduck
@Wilduck, people with low rep can't make comments. See Jeff Atwoods current thinking: http://meta.stackoverflow.com/questions/34464/questions-with-lots-of-thank-you-answers/51066#51066
Mark Ransom
@Wilduck, Like Ransom mentioned, this was the only way I could get additional information. As it is, this is the only answer I can comment on. I'm updating the answer, though it's rather close to yours, and less efficient.
thegrinner
When I try this is says there is no large_file_name. I made a file called this as a .txt file and saved it to the python folder. whats wrong?
novak
I'm not certain - what's the traceback show? It could be looking in the wrong location for the file. I see above it looks like you got it to work using Wilduck's method - no need to post again if you did.
thegrinner
A: 

First, open the big file for reading.

Second, open all the smaller file names for writing.

Third, iterate through every line. Every iteration, check to see what kind of line it is, then write it to that file.

More info on File I/O: http://docs.python.org/tutorial/inputoutput.html

orangeoctopus
+5  A: 

You're probably going to want to do something like this:

big_file = open('big_file', 'r')
small_file1 = open('small_file1', 'w')
small_file2 = open('small_file2', 'w')

for line in big_file:
    if 'Charlie' in line: small_file1.write(line)
    if 'Mark' in line: small_file2.write(line)

big_file.close()
small_file1.close()
small_file2.close()

Opening a file for reading returns an object that allows you to iterate over the lines. You can then check each line (which is just a string of whatever that line contains) for whatever condition you want, then write it to the appropriate file that you opened for writing. It is worth noting that when you open a file with 'w' it will overwrite anything already written to that file. If you want to simply add to the end, you should open it with 'a', to append.

Additionally, if you expect there to be some possibility of error in your reading/writing code, and want to make sure the files are closed, you can use:

with open('big_file', 'r') as big_file:
    <do stuff prone to error>
Wilduck
it keeps giving me an error with invalid syntax for line 5 what gives?
novak
More context please. What error, what code?
Wilduck
it just says invalid syntax and highlights the ':' at the end of this line if 'Charlie' in line: small_file1.write(line):
novak
Traceback (most recent call last): File "<string>", line 6, in <fragment>Syntax Error: if 'Charlie' in line: small_file1.write(line):: <string>, line 650>>> thats the error now
novak
Oh. There shouldn't be a colon at the very end of that line. My bad. It's fixed in my answer now.
Wilduck
Thanks, but now it says Traceback (most recent call last): File "C:/Python26/bigtsmall", line 1, in <module> big_file = open('big_file', 'r')IOError: [Errno 2] No such file or directory: 'big_file'I made a text file called 'big_file' and its in the python directory what am i doing wrong here?
novak
Well, there are a number of things that could be going wrong. First, you have to include the full filename of the file. So if you named the file 'big_file.txt', you need to include the '.txt'. Also, it looks like you are already doing this, but be sure to include the quotes around the name of the file.
Wilduck
so I named the file big_file and its a .txt file: i wrote this codeand it says Traceback (most recent call last): File "C:/Python26/bigtsmall", line 1, in <module> big_file = open('big_file.txt', 'r')IOError: [Errno 2] No such file or directory: 'big_file.txt'here is my codebig_file = open('big_file.txt', 'r')small_file1 = open('small_file1.txt', 'w')small_file2 = open('small_file2.txt', 'w')for line in big_file: if 'Charlie' in line: small_file1.write(line) if 'Mark' in line: small_file2.write(line)big_file.close()small_file1.close()small_file2.close()
novak
Are you sure the text file is in the same file as your python script? To check, you can use 'import os' on one line and 'print os.getcwd()' on another to have your script (or the interpreter) print the directory you're working in. If it's different than the one you saved the file in, you'll have to provide the full path name to the file.
Wilduck
how do i provide the full path name to the file?
novak
It depends on the operating system. It looks like you're in windows, so something that looks like 'C:\\path\\to\\file.txt' should work. There are double slashes since '\' is a special character and needs to be escaped. If you don't like how that looks you can use a raw string like so r'C:\path\to\file.txt'.
Wilduck
Also, as soon as this is working for you, please mark the check under this answer to accept it as the best answer.
Wilduck
And this section of dive into python might be worth reading: http://diveintopython.org/file_handling/file_objects.html
Wilduck
Now it says Traceback (most recent call last): File "C:/Python26/bigtsmall", line 1, in <module> big_file = open('C:\Python2.6\big_file.txt', 'r')IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Python2.6\x08ig_file.txt'
novak
what am i dong wrong he3re is my code as it is now big_file = open('C:\Python2.6\big_file.txt', 'r')small_file1 = open('C:\Python2.6\small_file1.txt', 'w')small_file2 = open('C:\Python2.6\small_file2.txt', 'w')for line in big_file: if 'Charlie' in line: small_file1.write(line) if 'Mark' in line: small_file2.write(line)big_file.close()small_file1.close()small_file2.close()
novak
YAY i got it to work thanks mate!
novak
Glad that it's working!
Wilduck