join() 有一个定义 str.join(iterable) 其中iterable 是生成器或列表或集合等。因此,如果您已经从文件中读取了一个字符串列表并且您正在使用 join 将它们连接起来,这将很有帮助。
例如
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))
numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))
s1 = 'abc'
s2 = '123'
""" Each character of s2 is concatenated to the front of s1"""
print('s1.join(s2):', s1.join(s2))
""" Each character of s1 is concatenated to the front of s2"""
print('s2.join(s1):', s2.join(s1))
您可以使用 ''.join(readlines(f)) 之类的连接来获取文件中的所有行
现在您可以使用 fileinput 模块使用 join 完成您的任务
import fileinput
files= ['package-lock.json', 'sqldump.sql', 'felony.json', 'maindata.csv']
allfiles = fileinput.input(files)
all_text = ''.join(allfiles)
请参阅this answer 了解将文件连接成字符串的最有效方法。
建议:正如您提到的会有数百万行,您是否考虑过将其存储在变量中所消耗的内存?因此,最好在读取行时立即执行您计划执行的操作,而不是将其存储在变量中。