Python program to open a text file and if the first word of line is "a" or"A" replace it with "M".
Answers
Explanation:
Use str. replace() to replace a string within a file
strip() to strip the end-line break. Then call str. replace(old, new) to replace old with new in the line
Answer:
The fileObj returned after the file is opened maintains a file pointer. It initially positions at the beginning of the file and advances whenever read/write operations are performed.
Reading Line/Lines from a Text File
fileObj.readline() -> str: (most commonly-used) Read next line (upto and include newline) and return a string (including newline). It returns an empty string after the end-of-file (EOF).
fileObj.readlines() -> [str]: Read all lines into a list of strings.
fileObj.read() -> str: Read the entire file into a string.
Writing Line to a Text File
fileObj.write(str) -> int: Write the given string to the file and return the number of characters written. You need to explicitly terminate the str with a '\n', if needed. The '\n' will be translated to the platform-dependent newline ('\r\n' for Windows or '\n' for Unixes/Mac OS).