码迷,mamicode.com
首页 > 编程语言 > 详细

Python Files

时间:2020-01-07 20:12:37      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:erp   ring   method   cte   disk   ret   list   contain   pen   

ython 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']
'''

Python Files

标签:erp   ring   method   cte   disk   ret   list   contain   pen   

原文地址:https://www.cnblogs.com/bit-happens/p/12163299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!