open(file_address access_mode)Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object. There are different types of access_modes:
r: Opens a file for reading only r+: Opens a file for both reading and writing w: Opens a file for writing only w+: Open a file for writing and reading. a: Opens a file for appending a+: Opens a file for both appending and readingWhen you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text.
# Reading a file f = open(__file__ 'r') #read() text = f.read(10) print(text) f.close()
# Reading a line in a file f = open(__file__ 'r') #readline() text = f.readline(20) print(text) f.close()
# Reading a file f = open(__file__ 'r') #readline() text = f.readlines(25) print(text) f.close()
# Writing a file f = open(__file__ 'w') line = 'Welcome Geeksn' #write() f.write(line) f.close()
Още примери в различни режими: Python # Reading and Writing a file f = open(__file__ 'r+') lines = f.read() f.write(lines) f.close()
Python # Writing and Reading a file f = open(__file__ 'w+') lines = f.read() f.write(lines) f.close()
Python # Appending a file f = open(__file__ 'a') lines = 'Welcome Geeksn' f.write(lines) f.close()
Python # Appending and reading a file f = open(__file__ 'a+') lines = f.read() f.write(lines) f.close()
# Writing a file f = open(__file__ 'a+') lines = f.readlines() #writelines() f.writelines(lines) f.close()
# Telling the file object position f = open(__file__ 'r') lines = f.read(10) #tell() print(f.tell()) f.close()
# Setting the file object position f = open(__file__ 'r') lines = f.read(10) print(lines) #seek() print(f.seek(22)) lines = f.read(10) print(lines) f.close()
# Clearing the internal buffer before closing the file f = open(__file__ 'r') lines = f.read(10) #flush() f.flush() print(f.read()) f.close()
# Getting the integer file descriptor f = open(__file__ 'r') #fileno() print(f.fileno()) f.close()
# Checks if file is connected to a tty(-like) device f = open(__file__ 'r') #isatty() print(f.isatty()) f.close()
# Iterates over the file f = open(__file__ 'r') #next() try: while f.next(): print(f.next()) except: f.close()
# Truncates the file f = open(__file__ 'w') #truncate() f.truncate(10) f.close()
# Opening and closing a file f = open(__file__ 'r') #close() f.close()
f = open(__file__ 'a+') print(f.closed) print(f.encoding) print(f.mode) print(f.newlines) print(f.softspace)
Свързана статия: Четене и писане в текстови файлове в Python Справка: https://docs.python.org/2.4/lib/bltin-file-objects.html