如何在不重复代码的情况下打开多个文件

2024-05-18 07:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: ofthekey代码txtopenthisaudio
3条回答

将代码放入函数中:

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

然后多次调用这个函数:

Audio = openandread("Key Words\Audio.txt")
Calls = openandread("Key Words\Calls.txt")
Charging = openandread("Key Words\Charging.txt")

或者如果你想把它缩短一些:

Audio, Calls, Charging = (openandread(i) for i in ["Key Words\Audio.txt", "Key Words\Calls.txt", "Key Words\Charging.txt"])

这就是函数的用途:

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

列出需要打开的文件:

files_to_open = [
    'file_1.txt',
    'file_2.txt'
]

calls_info = {}

迭代列表,打开并处理:

for file_ in files_to_open:
    with open(file_) as f:
        calls_info[file_] = f.read().splitlines()

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

calls_info[file_path] # Make sure file_path is the right path you put in the list!

相关问题 更多 >