先上寫干貨,幾個開源網站:
- [github.com](#)
- [launchpad.net](#)
- [gitorious.org](#)
- [sourceforge.net](#)
- [freecode.com](#)
今天介紹一下python函數和文件讀寫的知識。
### 函數
###
~~~
def print_two(*args):#That tells Python to take all the arguments to the function and then put them in args as a list
arg1,arg2=args
print "arg1: %r, arg2: %r"%(arg1,arg2)
def print_two_again(arg1,arg2):
print "arg: %r,arg: %r"%(arg1,arg2)
def print_one(arg1):
print "arg1: %r" %arg1
def print_none():
print "I got nothin'."
return ;
print_two("zed","shaw")
print_two_again("zed","shaw")
print_one("First!")
print_none()
~~~
~~~
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
~~~
### 文件讀寫
**讀寫取方法:**
?**read()**?方法用來直接讀取字節到字符串中, 不帶參數表示全部讀取,參數表示讀取多少個字節
?**readline()** 方法讀取打開文件的一行,如果提供參數表示讀取字節數,默認參數是-1,代表行的結尾
?**readlines()**方法會讀取所有(剩余的)行然后把他們作為一個字符串列表返回。可選參數代表返回的最大字節大小。
**輸出方法:**
? ?**write()**?方法表示寫入到文件中去
? ?**writelines()**? 方法是針對列表的操作,接受一個字符串列表作為參數,寫入文件。行結束符不會自動加入。
**核心筆記:**使用輸入方法read() 或者 readlines() 從文件中讀取行時,python并不會刪除行結尾符。 ??
**文件內移動:**
???**seek()**?方法,移動文件指針到不同的位置。
? ??**tell()**?顯示文件當前指針的位置。
**文件內建屬性**
? ?file.name ? ? ? 返回文件名(包含路徑)
? ? ?file.mode ? ? ? 返回文件打開模式
? ? ?file.closed ? ? ?返回文件是否已經關閉
? ? ?file.encoding ? 返回文件的編碼
~~~
input_file=raw_input("input_file: ")
def print_all(f):
print f.read()
def rewind(f):
f.seek(24)#seek 24 characters
def print_a_line(line_count,f):
print line_count,f.readline()
current_file=open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's rewing,kind of like a tape."
rewind(current_file)
print" Let's print three lines: "
current_line = 1
print_a_line(current_line,current_file)
current_line=current_line+1
print_a_line(current_line,current_file)
current_line=current_line+1
print_a_line(current_line,current_file)
~~~
如果文件是配置文件,可以用下面的代碼來調用:
~~~
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'刪掉
~~~
更詳細的介紹請點擊:[http://www.cnblogs.com/NNUF/archive/2013/01/22/2872234.html](http://www.cnblogs.com/NNUF/archive/2013/01/22/2872234.html)