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

时间:2016-02-24 22:21:49

标签: python file python-3.4

我正在制作一个可以打开多个文件的程序,它们都非常相似。 All在记事本上包含一些小写的单行字。我不想多次重复代码。理想情况下,我想使用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).

5 个答案:

答案 0 :(得分:1)

这就是以下功能:

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 :(得分:0)

列出您需要打开的文件:

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!

答案 2 :(得分:0)

将代码放入函数中:

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"])

答案 3 :(得分:0)

试试这个

Audio = []
Calls = []
Charging = []    
FILES_LISTS = (
  ( "Key Words\Audio.txt", Audio ),
  ( "Key Words\Calls.txt", Calls ),
  ( "Key Words\Charging.txt", Charging )
)
for file_name, list_var in FILES_LISTS:
  File = open( file_name, 'r' )
  list_var += File.read().splitlines()
  File.close()

确保键入list_var +=而不是list_var =。这是有效的,因为列表是可变的,因为python与引用一起工作。

答案 4 :(得分:0)

您可以尝试unipath

# Install
$easy_install unipath

# In python
from unipath import Path

t1 = Path('Key Words\Audio.txt')
...