Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k 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 (36.8k 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.

Browse Categories

...