如何通过python打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19508703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:56:08  来源:igfitidea点击:

How to Open a file through python

pythonfunctionpython-3.x

提问by user2891763

I am very new to programming and the python language.

我对编程和 python 语言很陌生。

I know how to open a file in python, but the question is how can I open the file as a parameter of a function?

我知道如何在 python 中打开文件,但问题是如何将文件作为函数的参数打开?

example:

例子:

function(parameter)

Here is how I have written out the code:

这是我写出代码的方式:

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

采纳答案by aIKid

You can easily pass the file object.

您可以轻松传递文件对象。

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

and in your function, return the list of lines

并在您的函数中,返回行列表

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

Another trick, python file objects actually have a method to read the lines of the file. Like this:

另一个技巧,python文件对象实际上有一个方法来读取文件的行。像这样:

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

With the second method, readlinesis like your function. You don't have to call it again.

用第二种方法,readlines就像你的函数。您不必再次调用它。

UpdateHere is how you should write your code:

更新以下是您应该如何编写代码:

First method:

第一种方法:

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)

Second one:

第二个:

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

Hope this helps!

希望这可以帮助!

回答by Stephen Hosea

Python allows to put multiple open() statements in a single with. You comma-separate them. Your code would then be:

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

And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)

不,通过在函数末尾放置显式返回,您不会获得任何收益。您可以使用 return 提前退出,但您在最后拥有它,并且该函数将在没有它的情况下退出。(当然,对于返回值的函数,您可以使用 return 来指定要返回的值。)

回答by Siva Cn

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

or you can even modify this, such a way it takes file object as a function arguement as well

或者你甚至可以修改它,这样它也可以将文件对象作为函数参数

回答by John Don

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)

回答by G.Bhalla

Here's a much simpler way of opening a file without defining your own function in Python 3.4:

这是一种更简单的打开文件的方法,无需在 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

Here are the types of files:

以下是文件类型:

  • "r": just to read a file

  • "w": just to write a file

  • "r+": a special type which allows both reading and writing of the file

  • "r": 只是为了读取文件

  • "w": 只是为了写一个文件

  • "r+": 允许读取和写入文件的特殊类型

For more information see this cheatsheet.

有关更多信息,请参阅此备忘单