我正在做一个程序,将打开多个文件,他们都非常相似。在记事本上包含几个小写的单字行。我不想重复代码多次。理想情况下,我希望使用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).
将代码放入函数中:
然后多次调用这个函数:
或者如果你想把它缩短一些:
这就是函数的用途:
列出需要打开的文件:
迭代列表,打开并处理:
在这里,我创建了一个
calls_info
变量。这样做就是把所有的东西都存储在字典里。它们包含键和值—要访问文件的值,只需按如下方式对其进行索引:相关问题 更多 >
编程相关推荐