what is the fgets() equivalent in Python [duplicate] - python

This question already has answers here:
Read only the first line of a file?
(8 answers)
Closed 3 months ago.
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?

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

Related

Why my file end up blank when I try to remove characters? [duplicate]

This question already has answers here:
replacing text in a file with Python
(7 answers)
What is the best way to modify a text file in-place?
(4 answers)
Closed 1 year ago.
I followed this subject here because I want to remove the <br /> that are in my output text file.
So my code is the following one :
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt', 'r') as infile, open('comments_'+video_id+'.txt', 'w') as outfile:
temp = infile.read().replace("<br />", "")
outfile.write(temp)
If I remove this function call my file has content, but after I call this function my file is empty. Where did I do something wrong ?
Opening a file in w mode truncates the file first. So there's nothing to read from the file.
Read the file first, then open it for writing.
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt', 'r') as infile:
temp = infile.read().replace("<br />", "")
with open('comments_'+video_id+'.txt', 'w') as outfile:
outfile.write(temp)

for loop in file handling (python) [duplicate]

This question already has answers here:
Understanding file iteration in Python
(5 answers)
Closed 2 years ago.
f = open("food.txt", "r")
for line in f:
print(line)
I don't understand how the above for loop reads the file line by line? Why not character by character or word by word?
please explain.
That's how Python works, open creates a file-object.
If you look at I/O documentation for file objects by default they read line by line!
In words from documentation: "this is memory efficient, fast, and leads to simple code"
In the previous versions of Python(2.2-), you had to specify byte limit for the same functionality!
For characters you can do:
for line in f:
for c in line: print(c)
For words you can do:
for line in f:
for w in line.split(): print(w)

Python - Write list to text file with \n from re.findall [duplicate]

This question already has answers here:
Writing a list to a file with Python, with newlines
(26 answers)
Closed 5 years ago.
In reference to a previous question Python Regex - Capture match and previous two lines
I am try to write this match to a text file but it seems to write all the matches on 1 line.
Tried these combinations with no luck
output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', f.read())
myfilename.write(str(list(output) + '\n')) # gives me TypeError: can only concatenate list (not "str") to list
myfilename.write(str(output)) # writes to one line
Would I need a for loop to iterate each index to a new line, or am I missing something, it should be matching the CRLLF and keep the original format correct?
You could use
with open ("file_here.txt", "r") as fin, open("output.txt", "w") as fout:
output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', fin.read())
fout.write("\n".join(output))

Write to the last line of a text file? [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 1 year ago.
I am trying to get the program to automatically start at the last line of a text file when I run it and make it write on the last line. My current code is as follows:
with open('textfile.txt', 'a+') as tf
last_line = tf.readlines()[-1]
tf.write(linetext + '\n')`
When I run this, it says that the list index is out of range. How do I get this to automatically skip to the last line of a text file and start writing from there?
Use the a flag while opening the file
with open('path/to/file', 'a') as outfile:
outfile.write("This is the new last line\n")

Python. Read file by line from a point midway through (by byte) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python: how to jump to a particular line in a huge text file?
I'm trying to read various lines out of a large (250Mb) file.
The header tells me where certain parts are, i.e. the history subsection of the file starts at byte 241817341.
So is there a way to read the file only starting at that byte, without having to go through the rest of the file first? Something like:
file = open(file_name,'r')
history_line = file.readline(241817341)
while history_line != 'End':
history_line = file.readline()
[Do something with that line]
Is that sort of thing feasible?
f.seek(0)
print f.readline()
>>> Hello, world!
f.seek(4)
print f.readline()
>>> o, world!

Categories

Resources