我正在制作一个程序,将打开多个文件,它们都是非常相似的。在记事本上都有几行小写字。我不想重复代码多次。理想情况下,我希望使用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).发布于 2016-02-24 22:28:09
这就是职能所在:
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')发布于 2016-02-24 22:27:42
列出您需要打开的文件列表:
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!发布于 2016-02-24 22:29:01
将代码放入一个函数中:
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"])https://stackoverflow.com/questions/35614393
复制相似问题