2013-10-22 58 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