# mode=a 追加到文件的最后 with open('test.txt', 'a', encoding='utf-8') as fb: fb.write(
'关注《Python之王》公众号\n') with open('test.txt', 'a'encoding='utf-8') as fb: fb.write('作者:Runsen\n')
# with context manager with open("new.txt", "w") as f: print(f.closed) f.write("Hello World!") print(f.closed)
#输出如下 False True
如何批量读取多个文件
下面,批量读取某文件夹下的txt文件
file_list = ['1.txt', '2.txt', '3.txt','4.txt'] for path in file_list: with open(path, encoding='utf-8') as f: for line in f: print(line)
下面将批量读取文件夹下的txt文件的内容,合并内容到一个新文件5.txt中,具体实现的代码如下。
import os #获取目标文件夹的路径 filedir = os.getcwd()+'\\'+'\\txt' #获取当前文件夹中的文件名称列表 filenames = [] for i in os.listdir(filedir): if i.split(".")[-1] == 'txt': filenames.append(i) #打开当前目录下的5.txt文件,如果没有则创建 f = open('5.txt','w') #先遍历文件名 for filename in filenames: filepath = filedir+'\\'+filename #遍历单个文件,读取行数 for line in open(filepath,encoding='utf-8'): f.writelines(line) f.write('\n') #关闭文件 f.close()
其实在Window中只需要cd 至目标文件夹,即你需要将所有想要合并的txt文件添加至目标文件夹中,执行如下DOS命令 type *.txt > C:\目标路径\合并后的文件名.txt
def create_mac(): MAC='01-AF-3B' hex_num =string.hexdigits #0123456789abcdefABCDEF for i in range(3): n = random.sample(hex_num,2) sn = '-' + ''.join(n).upper() MAC += sn return MAC
def main(): with open('mac.txt','w') as f: for i in range(100): mac = create_mac() print(mac) f.write(mac+'\n')