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')
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')
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允许在一个with中放置多个open()语句。你用逗号分隔它们。你的代码是:
不,在函数的末尾加上显式的返回不会得到任何结果。您可以使用return提前退出,但在结束时使用了return,函数将在没有return的情况下退出。(当然,对于返回值的函数,可以使用return指定要返回的值。)
或者您甚至可以修改它,这样它也可以将file对象作为函数参数
您可以轻松地传递文件对象。
在函数中,返回行列表
另一个技巧是,python文件对象实际上有一个读取文件行的方法。像这样:
对于第二种方法,
readlines
就像您的函数。你不用再打电话了。更新 下面是编写代码的方法:
第一种方法:
第二个:
希望这有帮助!
相关问题 更多 >
编程相关推荐