Python Files

Python Files

In short, the built-in open function creates a Python file object, which serves as a link to an external file residing on your machine.

what is input or output?

  1. input means the file will be input source
  2. output means the file will be output target

file object's close method

  • terminates your connection to the external file
  • releases its system resources
  • flushes its buffered output to disk if any is still in memory.
'''Files in Action '''

# ------- write method for output ------- #
outputFile = open('myfile.txt', 'w')                                    # open for text output: create if file not exist
outputFile.write('hello text file\n')                                   # write a line of text: string
outputFile.write('\n')
print(outputFile.write('goodbye text file\n'))                          # return the number of characters written in Python 3.X
outputFile.close()                                                      # flush output buffers to disk

# ------- read method for input ------- #
# f.read()
# f.readline()
# f.readlines()
# file iterator

print('# ------- f.read() ------- #')
inputFile1 = open('myfile.txt')                                         # open for text input: 'r' is default
print(inputFile1.read())                                                # read all at once into string, print() interpret the end-of-line characters                                 


print('# ------- f.readline() ------- #')
inputFile2 = open('myfile.txt')
while True:
    line = inputFile2.readline()
    if line:                                                            # empty string: end-of-file
        print(line)                                                     # empty lines in the file come back as strings 
    else:                                                               # containing just a newline character, not as empty strings
        break

print('# ------- file iterators ------- #')
for line in open('myfile.txt'):
    print(line,end='')

print('# ------- f.readlines() ------- #')
inputFile3 = open('myfile.txt')
linelist = inputFile3.readlines()
print(linelist)


'''
18
# ------- f.read() ------- #
hello text file

goodbye text file

# ------- f.readline() ------- #
hello text file



goodbye text file

# ------- file iterators ------- #
hello text file

goodbye text file
# ------- f.readlines() ------- #
['hello text file\n', '\n', 'goodbye text file\n']
'''

posted @ 2020-01-07 19:19  bit_happens  阅读(106)  评论(0)    收藏  举报