2013-10-22 54 views
5

我對編程和python語言非常陌生。如何通過python打開文件

我知道如何在python中打開文件,但問題是如何打開文件作爲函數的參數?

例如:

function(parameter) 

這裏是我已經寫了代碼:

def function(file): 
    with open('file.txt', 'r') as f: 
     contents = f.readlines() 
    lines = [] 
    for line in f: 
     lines.append(line) 
    print(contents)  
+0

不太清楚。你想用它做什麼?你想傳遞文件對象,內容還是什麼?快點,否則你會陷入低谷。 – aIKid

+0

哦我想讀取文件 – user2891763

+0

你的意思是你想傳遞文件內容,作爲參數? – aIKid

回答

7

您可以輕鬆地傳遞文件對象。

with open('file.txt', 'r') as f: #open the file 
    contents = function(f) #put the lines to a variable. 

,並在你的函數,返回行

def function(file): 
    lines = [] 
    for line in f: 
     lines.append(line) 
    return lines 

另一個竅門的列表,Python文件對象實際上有讀取文件的行的方法。像這樣:

with open('file.txt', 'r') as f: #open the file 
    contents = f.readlines() #put the lines to a variable (list). 

使用第二種方法,readlines就像你的功能。您不必再次調用它。

更新 這裏是你應該怎麼寫代碼:

第一種方法:

def function(file): 
    lines = [] 
    for line in f: 
     lines.append(line) 
    return lines 
with open('file.txt', 'r') as f: #open the file 
    contents = function(f) #put the lines to a variable (list). 
    print(contents) 

第二個:

with open('file.txt', 'r') as f: #open the file 
    contents = f.readlines() #put the lines to a variable (list). 
    print(contents) 

希望這有助於!

+0

嘗試'lines = f.readlines()' – Murph

+0

這是什麼意思:SyntaxError:'return'功能 – user2891763

+0

抱歉,抱歉。現在修復它。錯誤的縮進。 – aIKid

0

Python允許把多個打開的()語句在一個單一的與。你用逗號分開它們。您的代碼將是:

def filter(txt, oldfile, newfile): 
    '''\ 
    Read a list of names from a file line by line into an output file. 
    If a line begins with a particular name, insert a string of text 
    after the name before appending the line to the output file. 
    ''' 

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile: 
     for line in infile: 
      if line.startswith(txt): 
       line = line[0:len(txt)] + ' - Truly a great person!\n' 
      outfile.write(line) 

# input the name you want to check against 
text = input('Please enter the name of a great person: ')  
letsgo = filter(text,'Spanish', 'Spanish2') 

而且不,你不會在你的函數的末尾加一個明確的返回來獲得任何東西。你可以使用return來儘早退出,但最後你會得到它,並且沒有它,函數將退出。 (當然,如果函數返回一個值,則使用return來指定要返回的值。)

0
def fun(file): 
    contents = None 

    with open(file, 'r') as fp: 
     contents = fp.readlines() 

    ## if you want to eliminate all blank lines uncomment the next line 
    #contents = [line for line in ''.join(contents).splitlines() if line] 

    return contents 

print fun('test_file.txt') 

或者你甚至可以修改此,這種方式需要的文件對象作爲函數arguement以及

+0

如果你打算使用'splitlines'去除行中的換行符和/或空行消除,你最好將它作爲一個單值並分割,或逐行處理。將所有行讀入'list','加入'list',然後'split'再次浪費工作/內存(你一次存儲三份文件數據)。 – ShadowRanger

+0

對於沒有換行符的行的列表,你可以通過'contents = f.read()將時間最小化(如果你有足夠的內存)。splitlines()'(它將峯值內存的一個副本作爲一個塊丟棄,或者沒有空行(並且在內存中一次只有兩個副本),'contents = list(filter(None,f.read()。splitlines()))'' 。如果只有一個副本作爲'list',在內存中沒有完整的數據副本,請逐行處理它,並且隨着過濾條件和過濾器一起處理:'contents = [x for(x.rstrip('\ r \ n')for x in f)if [ – ShadowRanger

+0

]呵呵,爲了完整起見,如果你想去除所有尾隨的空白(不僅僅是換行符),然後去掉空白行,它可以優化爲'contents = list(過濾器(None,map(str.rstrip,f)))''將所有工作移動到CPython中的C層,代價是使用'map'和'filter',通常認爲Pythonic更少。僅剝離換行符也可以這樣做,它只是更醜陋而已:'from operator import methodcaller','contents = list(filter(None,map(methodcaller('strip','\ r \ n'),f)))'' – ShadowRanger

-2
def main(): 
     file=open("chirag.txt","r") 
     for n in file: 
       print (n.strip("t")) 
     file.close() 
if __name__== "__main__": 
     main() 


the other method is 


with open("chirag.txt","r") as f: 
     for n in f: 
       print(n) 
+2

這對現有答案沒有任何幫助,格式很糟糕,並且使用顯式'close'而不是''with''作爲主要示例,這只是鼓勵不好的做法。 – ShadowRanger