-2

I have a text file which needs to be separated line by line into individual text files. So if the main file contains the strings:

foo
bar
bla

I would have 3 files which could be named numerically 1.txt (containing the string "foo"), 2.txt (sontaining the string"bar") and 3.txt (containing the string "bla")

The straightforward way to do with would be to open three files for writing and writing line by line into each file. But the problem is when we have lot of lines or we do not know exactly how many there are. It seems painfully unnecessary to have to create

f1=open('main_file', 'r')
f2=open('1.txt', 'w')
f3=open('2.txt', 'w')
f4=open('3.txt', 'w')

is there a way to put a counter in this operation or a library which can handle this type of ask?

badner
  • 768
  • 2
  • 10
  • 31

3 Answers3

2

Read the lines from the file in a loop, maintaining the line number; open a file with the name derived from the line number, and write the line into the file:

f1 = open('main_file', 'r')
for i,text in enumerate(f1):
    open(str(i + 1) + '.txt', 'w').write(text)
DYZ
  • 55,249
  • 10
  • 64
  • 93
2

You would want something like this. Using with is the preferred way for dealing with files, since it automatically closes them for you after the with scope.

with open('main_file', 'r') as in_file:
  for line_number, line in enumerate(in_file):
    with open("{}.txt".format(i+1), 'w') as out_file:
      out_file.write(line) 
Hesham Attia
  • 979
  • 8
  • 13
0

Firstly you could read the file into a list, where each element stands for a row in the file.

with open('/path/to/data','r') as f:
    data = [line.strip() for line in f]

Then you could use a for loop to write into files separately.

for counter in range(len(data)):
    with open('/path/to/file/'+str(counter),'w') as f:
        f.write(data[counter])

Notes: Since you're continuously opening numerous files, I highly suggest using

with open() as f:
    #your operation

The advantage of using this is that you can make sure Python release the resources on time. Details: What's the advantage of using 'with .. as' statement in Python?

Community
  • 1
  • 1
Shawn. L
  • 403
  • 1
  • 3
  • 13