1

I am currently working with file handling in Python. I have problem in copying the string value of the file.

I wanted to copy the string from file and store it to a variable, just like in C

example: this is how we do in C

FILE *fptr = fopen("read.txt", "r");
fgets(charVar, 100, fptr);

where we store the string file to charVar. So is there a fgets() function equivalent to python?

1 Answers1

1

You can pass the limit argument to readline for a file object which would have similar behavior of stopping on a max character or a newline. Example text file:

01234567890123456789
01234567890123456789
with open("test.txt", "r") as f:
    while data := f.readline(8):
        print("line:", data)

Outputs:

line: 01234567
line: 89012345
line: 6789

line: 01234567
line: 89012345
line: 6789

flakes
  • 21,558
  • 8
  • 41
  • 88