首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何打开多个文件而不重复代码

如何打开多个文件而不重复代码
EN

Stack Overflow用户
提问于 2016-02-24 22:21:49
回答 5查看 180关注 0票数 1

我正在制作一个程序,将打开多个文件,它们都是非常相似的。在记事本上都有几行小写字。我不想重复代码多次。理想情况下,我希望使用while循环来重复代码,但更改它打开的文件,每次重复。有办法吗?这是当前的代码:

代码语言:javascript
复制
File = open("Key Words\Audio.txt","r") #This will open the file called Audio.
Audio = [] #This creates the Audio list
Audio = File.read().splitlines() #This saves everything on each line of the  Audio file to a diffrent section of the Audio list.


File = open("Key Words\Calls.txt","r") #This will open the file called Calls.
Calls = [] #This creates the Calls list
Calls = File.read().splitlines() #This saves everything on each line of the Calls file to a diffrent section of the Calls list.


File = open("Key Words\Charging.txt","r") #This will open the file called Charging.
Charging = [] #This creates the Charging list
Charging = File.read().splitlines() #This saves everything on each line of the Charging file to a diffrent section of the Charging list.

File.close() #This closes the File(s).
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-02-24 22:28:09

这就是职能所在:

代码语言:javascript
复制
def readfile(filepath):
    with open(filepath, 'r') as f:
        return f.read().splitlines()

audio = readfile('Key Words\Audio.txt')
calls = readfile('Key Words\Calls.txt')
charging = readfile('Key Words\Charging.txt')
票数 1
EN

Stack Overflow用户

发布于 2016-02-24 22:27:42

列出您需要打开的文件列表:

代码语言:javascript
复制
files_to_open = [
    'file_1.txt',
    'file_2.txt'
]

calls_info = {}

遍历列表,然后打开并处理:

代码语言:javascript
复制
for file_ in files_to_open:
    with open(file_) as f:
        calls_info[file_] = f.read().splitlines()

在这里,我创建了一个calls_info变量。这样做的目的是把所有的东西都储存在字典里。这些保存键和值-要访问文件的值,只需按如下方式对其进行索引:

代码语言:javascript
复制
calls_info[file_path] # Make sure file_path is the right path you put in the list!
票数 0
EN

Stack Overflow用户

发布于 2016-02-24 22:29:01

将代码放入一个函数中:

代码语言:javascript
复制
def openandread(filename):
    # No need to close the file if you use with:
    with open(filename,"r") as File:
        return_this = File.read().splitlines()
    return return_this

然后只需多次调用此函数:

代码语言:javascript
复制
Audio = openandread("Key Words\Audio.txt")
Calls = openandread("Key Words\Calls.txt")
Charging = openandread("Key Words\Charging.txt")

或者如果你想让它更短:

代码语言:javascript
复制
Audio, Calls, Charging = (openandread(i) for i in ["Key Words\Audio.txt", "Key Words\Calls.txt", "Key Words\Charging.txt"])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35614393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档