簡體   English   中英

如何通過python打開文件

[英]How to Open a file through 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)    

您可以輕松傳遞文件對象。

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)

希望這可以幫助!

Python 允許將多個 open() 語句放在一個 with 中。 你用逗號分隔它們。 您的代碼將是:

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 來指定要返回的值。)

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')

或者你甚至可以修改它,這樣它也可以將文件對象作為函數參數

這是一種更簡單的打開文件的方法,無需在 Python 3.4 中定義自己的函數:

var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file

以下是文件類型:

  • "r" : 只是為了讀取文件

  • "w" : 只是寫一個文件

  • "r+" : 一種允許讀寫文件的特殊類型

有關更多信息,請參閱此備忘單

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM