Python Script to write myFile.txt:
The best option to writing text file is using "with" keyword. First we will create the file object f and then f.write('string_content\n') will create text file and write the content into text file.
The above piece of code will create a myFile.txt file in the current directory means in the same location where we are keeping the script. You can give any path for the output file.
Python Script to read myFile.txt:
Use open() and create a file object "f" and the f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string.
The best option to writing text file is using "with" keyword. First we will create the file object f and then f.write('string_content\n') will create text file and write the content into text file.
with open('myFile.txt', 'a') as f: f.write("This is the test string01\n")
The above piece of code will create a myFile.txt file in the current directory means in the same location where we are keeping the script. You can give any path for the output file.
with open('D:\myFile.txt', 'a') as f: f.write("This is the test string01\n")Once we create file object we can write many strings into the file.
with open('D:\myFile.txt', 'a') as f: f.write("This is the test string01\n") f.write("This is the test string02\n") f.write("This is the test string02\n")
Python Script to read myFile.txt:
Use open() and create a file object "f" and the f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string.
f=open('myFile.txt', 'r') f.readline() 'This is the test string01\n' f.readline() 'This is the test string02\n' f.readline() 'This is the test string02\n' f.readline() ''f.readlines() will print all lines of the file as a list.
f=open('myFile.txt', 'r') f.readlines() ['This is the test string01\n', 'This is the test string02\n', 'This is the test string02\n']So finally the best way to read the file line by line is first take all lines into list using f.readlines() and then iterate the list.
f=open('myFile.txt', 'r') fList=f.readlines() for line in fList: print line This is the test string01 This is the test string02 This is the test string02
- r : When the file will only be read
- w : When the file only writing (an existing file with the same name will be erased)
- a : Opens the file for appending; any data written to the file is automatically added to the end
- r+ : Opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.
- On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files
*********************************
No comments:
Post a Comment