Every programming language should have the facility of file handling. At least basic open, close, read, and write file records.
To access the file we have two options in python. One obviously to give the whole path in every file operations and another and the best one should be set your path of the files and access the files by only names.
This will create the current path of as the path given in the CHDIR parameter.
Basic syntax of open and read files
f = open(“months.txt”) <- open the file and assign file pointer to “f” and months.txt is saved in the above path.
print(f.read()) <- read all the records from months.txt and print the same in console.
But if we want to read the file by number of records we need to pass the parameters in read function like below
f.read(1) <- will read 1 character from the file from the current position of the file pointer.
If you pass 2 instead of 1 it will read 2 characters per execution of the read function.
If you want to read files by the line we need to execute below command
f.readlines() <- here also we can pass the parameter for the number of lines you want to read per execution of readlines function. By default it is one line per execution.
Open operation open the file by default in “read” mode, if you want to open the file to write (in write mode), we need to specifically mention it in the command like below
fout = open(“test_ex_out.txt”, “w“) ß open test_ex_out.txt file in write mode and assign file pointer to fout.
Then to write records we need to execute below “write” command
fout.write(“First line”) ß this will write “First line” in fout (test_ex_out.txt) file.
After reading from files or any user input we always need string functions to manipulate strings as per our need.
It will remove extra spaces and extra lines from the string.
This will split strings based on the parameter passed.
line.split(” – “)