Dear All,

I am opening a file called initialisation:

try:
  initFile = open("initialisation.dat", "r")
except IOError:
  print ("Initialisation file cannot be openned for reading")

I would like to read the contents of this file and then print them on several other files i.e. file1, file2, file3, file4, etc.

i am writing the following code which generates maxValues = 20 files but it only writes the content of the initFile in file1 and not the rest.

maxValue = 20
for i in range(1, maxValue+1, 1):
  onitFile = open("File%d.txt" % i, "w")
  fileHandle = initFile.readlines()
  for fileLine in fileHandle:
    onitFile.write(fileLine)
  onitFile.close()
initFile.close()

Could you please comment on how to fix this problem?

Thanks very much in advance.

Nicholas

Recommended Answers

All 3 Replies

Member Avatar for masterofpuppets

hi,
I think the problem is that you're using the readlines method in the loop. You only need to read the lines from the initial file once and just copy them in the other files, so try to move the readlines outside the loop like this:

initFile = open( "filename.txt", "r" )
fileHandle = initFile.readlines()

maxValue = 20
for i in range( 1, maxValue + 1 ):
  onitFile = open( "File%d.txt" % i, "w" )
  
  for fileLine in fileHandle:
    onitFile.write( fileLine )
  onitFile.close()
  
initFile.close()

this should work

hope this helps :)

You don't even need the readlines(). You can iterate on the file object directly. On the other hand, after the file has been read, the file position is at the end of the file, so you must use seek to go to the beginning of the file

initFile = open( "filename.txt", "r" )

maxValue = 20
for i in range( 1, maxValue + 1 ):
  onitFile = open( "File%d.txt" % i, "w" )
  initFile.seek(0) # go to the beginning of the input file
  for fileLine in initFile:
    onitFile.write( fileLine )
  onitFile.close()
  
initFile.close()

Note that since you're only copying the file, you should consider using shutil.copy like this

import shutil
maxValue = 20
for i in range( 1, maxValue + 1 ):
  shutil.copy("filename.txt", "File%d.txt" % i )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.