Skip to content

Instantly share code, notes, and snippets.

@dketov
Created December 11, 2011 20:56
Show Gist options
  • Save dketov/1462693 to your computer and use it in GitHub Desktop.
Save dketov/1462693 to your computer and use it in GitHub Desktop.
Файл
# -*- encoding: utf-8 -*-
"""
Открытие файла
"""
#open() returns a file object, and is most commonly used with two arguments:
#"open(filename, mode)".
f=open('/tmp/workfile', 'w')
print f
# mode can be 'r' when the file will only be read,
# 'w' for 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 and the Macintosh, 'b' appended to the mode opens the file in binary
# mode so there are also modes like 'rb', 'wb', and 'r+b'.
# -*- encoding: utf-8 -*-
"""
Закрытие файла
"""
# Open files consume system resources, and depending on the file mode,
# other programs may not be able to access them.
# It's important to close files as soon as you're finished with them, as shown in
#
f = open("/music/_singles/kairo.mp3", "rb")
print f.closed
f.close()
print f
print f.closed
# -*- encoding: utf-8 -*-
"""
Чтение из файла
"""
f = open(r'c:\text\somefile.txt')
print f.read()
f.close()
# -*- encoding: utf-8 -*-
"""
Чтение строк из файла
"""
f = open("filename")
for line in f.readlines():
print "Line: " + line
# -*- encoding: utf-8 -*-
"""
Запись в файл
"""
f = open(r'c:\text\somefile.txt', 'w')
f.write('this\nis no\nhaiku')
f.close()
# -*- encoding: utf-8 -*-
"""
Изменение позиции в файле
"""
f = open('/tmp/workfile', 'r+')
f.write('0123456789abcdef')
f.seek(5) # Go to the 6th byte in the file
print f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
print f.read(1)
f.close()
# -*- encoding: utf-8 -*-
"""
Запись строк в файл
"""
f = open(r'c:\text\somefile.txt')
lines = f.readlines()
f.close()
lines[1] = "isn't a\n"
f = open(r'c:\text\somefile.txt', 'w')
f.writelines(lines)
f.close()
# -*- encoding: utf-8 -*-
"""
Определение позиции в файле
"""
f = open(r'c:\text\somefile.txt')
f.read(3)
f.read(2)
f.tell()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment