2.7 base. (1) is here. (2) is here.
Declared using the def keyword.
>>> def test(arg):
... print(arg)
...
>>> test('hoge')
hoge
>>> test(arg="hogehoge")
hogehoge
If you add an asterisk before the argument, you can accept any number of arguments that do not specify a keyword.
>>> def test(a, b, *args):
... print(a, b, args)
...
>>> test(1, 2, 3, 4, 5)
(1, 2, (3, 4, 5))
#OK even in the sky
>>> test(1, 2)
(1, 2, ())
#Keywords cannot be specified
>>> test(1, 2, args = 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() got an unexpected keyword argument 'args'
If you define an argument with two asterisks, you can take an undefined argument with a keyword specified.
>>> def test(a, b, **args):
... print(a, b, args)
...
>>> test(1, 2, c=3, d=4)
1, 2, {'c' : 3, 'd' : 4} #Substituted as a dictionary
#No keyword is NG
>>> test(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 2 arguments (3 given)
Arguments like * val and ** args should be at the end of the argument list
>>> def test(arg="hogehoge"):
... print(arg)
...
>>> test()
hogehoge
Use the built-in function ʻopen ()`. The arguments are almost the same as C's fopen ().
>>> f = open("foo.txt", "r")
>>> s = f.read() #Read all file contents
>>> f.close
#In python3 series, file encoding/Has an argument that specifies the text encoding used for decoding
# f = open("foo.txt", "r", encoding='utf-8')
Python2 series open: http://docs.python.jp/2/library/functions.html?highlight=open#open
Python3 series open: http://docs.python.jp/3/library/functions.html?highlight=open#open
I'll omit it here, but there's a lot of information about Unicode support in Python3. For example this. http://postd.cc/why-python-3-exists/
The meaning of the second argument.
symbol | meaning |
---|---|
'r' | Open for reading(Default) |
'w' | Open for writing and the file is truncated first |
'x' | Open to exclusive generation and fail if the file exists |
'a' | Open for writing and add to the end if the file exists |
'b' | Binary mode |
't' | Text mode(Default) |
'+' | Open disk file for update(Read / write) |
f.read(size)
Reads the specified size (or the end of the file if omitted) from the file and returns a string.
f.readline(size)
Reads the specified number of lines (1 line if omitted) and returns a character string.
f.readlines(size)
Reads multiple lines from the file up to the specified number of lines (up to the end of the file if there is none) and returns a list with strings as elements.
sample: Process text file line by line
>>> f = open("test.txt", 'r')
>>> for line in f:
... print(line, end=" ") #Display line by line
f.write(str)
Write to a file by specifying a character string.
f.writelines(sequence)
Takes a sequence (list, etc.) that includes a string as an argument and writes it to a file (no newline character is added for each element).
Recommended Posts