06. File

最後更新: 2022-05-11

目錄

 


open(Built-in function: file)

 

Usage:

file_object = open(filename[, mode])

ie.

fo = open("test.txt")

for line in fo:
    print line

Remark

open = Constructor function for the "file" type

>>> open
<built-in function open>
>>> file
<type 'file'>

 * When opening a file, it's preferable to use open() instead of invoking this constructor directly.

 * file() has been removed since Python 3.0

 


file object

 

Mode:

  • r             # Default
  • r+          # open for reading and writing. Does not create file.
  • rb           # binary mode
  • r+b        #
  • a             # append mode
  • a+          # create file if it doesn't exist and open it in append mode
  • a[b]        # append binary mode
  • w[b]       #  only writing(an existing file with the same name will be erased)
  • w+         # create file if it doesn't exist and open it in write mode

close()

flush()

read()

f.read([size]) -> read at most size bytes, returned as a string.
f.read() -> reads the whole file
f.readline([size]) -> next line from the file, as a string.
readlines([size]) -> list of strings

write()

f.write(str) -> None.  Write string str to file.

# The sequence can be any iterable object producing strings,
# typically a list of strings. There is no return value.

f.writelines(sequence_of_strings) -> None.    Write the strings to the file.
                                                                    ( Note that newlines are not added. )

newline

fsave.write("some string" + '\n')

* Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

P.S.

* 當 file 不存在時: IOError: [Errno 2] No such file or directory <== 'r' mode
* IOError: File not open for writing => fsave=file("tmp.txt",'w')

position:

tell()

# print current file position, an integer (may be a long integer (byte)).

f.tell()

seek()

# offset is a byte count. (+/-)
# whence:

  • 0  absolute file positioning (Default)
  • 1  move relative to current position
  • 2  relative to end of file

f.seek(offset[, whence]) -> None

應用:

  • 回到檔案的頭: .seek(0)

truncate()

# Truncate the file to at most size bytes.

# Size defaults to the current file position, as returned by tell().

f.truncate([size]) -> None.

other:

f.name                     # file name
f.encoding                # None
f.mode                     # r

 


Clone File (By write)

 

fin = open('c:\\temp\\file.in', 'r')
fout = open('c:\\temp\\fine.out', 'w')
for line in f:
    fout.write(line.rstrip() + '\n')
f.close()
  • 'r'
  • 'w'
  • 'a' for append
  • 'rU' is the "Universal            # converting different line-endings as a simple '\n'.

 


Iteration

 

f = open(filename)
for line in f.readlines():
    process(line)

OR

f = open("test.txt")
for line in f:
    process(line)

OR

f = open(filename)
while True:
    line = f.readline()
    if not line: break
    process(line)

 

 |  __iter__(...)
 |      x.__iter__() <==> iter(x)

 


Lazy Line Iteration

 

import fileinput
for line in fileinput.input(filename):
    process(line)

 


Unicode Files

 

  f = codecs.open('foo.txt', 'rU', 'utf-8')
  for line in f:
      # here line is a *unicode* string

 


File Operation(Class: os)

 

i.e.

import os

os.path.exists(path) -- true if it exists

shutil.copy(source-path, dest-path) -- copy a file (dest path directories should exist)

os.path.dirname(path)
os.path.basename(path)
os.path.join(dir, filename)
filenames = os.listdir(dir)

os.stat(path)

# os.unlink(path)
os.rename("test1.txt", "test2.txt")

os.remove("test3.txt")

File

stat("path")

remove("path")

rename("path")

Folder

os.mkdir("tmp")              # makes a directory

os.makedirs(dir_path)     # makes all the needed dirs

os.rmdir("tmp")              # remove a directory

os.chdir("tmp")               # Change directory

os.chdir("..")

os.getcwd()

os.listdir(path)                # It does not include the special entries '.' and '..'

Permission

os.chmod(path, mode)

os.chown(path, uid, gid)

TMP

# It will be destroyed as soon as it is closed
# Return a new file object opened in update mode (w+b).

os.tmpfile()

# Return a unique path name that is reasonable for creating a temporary file.

os.tmpnam()

Link

# Create a symbolic link pointing to src named dst.

os.symlink(src, dst)

# Return a string representing the path to which the symbolic link points.

os.readlink(path)

 


glob

 

Return a possibly-empty list of path names that match pathname

Usage:

glob.glob(pathname)

Example:

from glob import glob

glob.glob('./*.txt')
# ['./1.txt', './2.txt']

glob('[0-9].*')
# ['1.txt', '2.txt']

Remark

*, ?,  [] ranges expressed will be correctly matched.

'[?]' matches the character '?'

 


Doc

 

https://docs.python.org/2/library/os.html

 

 

Creative Commons license icon Creative Commons license icon