如何通过python打开文件 [英] How to Open a file through python

查看:97
本文介绍了如何通过python打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

示例:

 函数(参数)

以下是我写出的代码:

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

解决方案

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

 打开('file.txt','r')为f:#打开文件
contents = function(f)#将行输入到一个变量中。

在你的函数中,返回行列表

  def函数(文件):
lines = []
for line in f:
lines.append(line)
返回行

另一个窍门是,python文件对象实际上有一个读取文件行的​​方法。像这样:

 与open('file.txt','r')作为f:#打开文件
contents = f.readlines()#把行输入到一个变量(列表)。

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



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



第一种方法:

  def函数(文件):
lines = []
用于f:
lines.append(line)
返回行
以open('file.txt','r')作为f:#open文件
contents = function(f)#将行输入到一个变量(列表)。
print(contents)

第二个:

 以open('file.txt','r')作为f:#打开文件
contents = f.readlines()#put将行一个变量(列表)。
print(contents)

希望这有助于您!


I am very new to programming and the python language.

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?

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)    

解决方案

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:

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

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

Update Here 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!

这篇关于如何通过python打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆