0 votes
1 view
in Data Science by (10.1k points)

I have a text file that has 1k lines.

After 100 lines I want to replace \r\n with, example:

1

2

3

4

5

6

7

8

9

10

Will be:

1,2,3,4,5

6,7,8,9,10

....

Which will result in 2 lines 1,2,3.. and 6,7...

1 Answer

0 votes
by (20.4k points)

This should work:

with open("Your/File/Path", "r+") as f:

    content = [(x.replace("\r\n", ", ") if i % 100 != 0 else x) for i, x in enumerate(f.readlines(), 1)]

    f.truncate(0)

    f.seek(0, 0)

    f.writelines(content)

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...