How to insert a newline at middle of a file in python
i am a new user of python. Just trying to write a script using python. Can someone help me out.
I calculate some values using data from a file, and 开发者_JAVA技巧i want to replace the existing value with the new value in the file along with that i would like to comment out the existing value so that i can verify whether the new calculated value does make sense. I did parse the required files and am messed up with the insertion of newline and commenting out the old one.
Would be greatful if someone posts an example.
Thanks n regards ss213
Output to a new file, line by line, changing what you need. Then replace the old file with the new one.
input = open('input.txt','r')
output = open('temp.txt','w')
for line in input.readlines():
if line == 'xxx':
output.write('#' + line)
output.write('yyy')
else:
output.write(line)
A bit vague. Let's suppose you have a string
a = 'ABCDEF'
and you want to insert a newline in the middle, then you can use:
a = "%s%s%s" % (a [:3], '\n', a [3:])
Or three bazillion other ways of doing it. Could you post an example input file and the desired output?
精彩评论