python的OS模块生成100个txt文件

 1 #!/user/bin/env/python35
 2 # -*-coding:utf-8-*-
 3 # author:Keekuun
 4 
 5 """
 6 问题:生成一个文件夹,文件夹下面生成100个txt文件,分别命名为1.txt ,2.txt到100.txt,
 7 其中1.txt内容为1到100,2.txt的内容为101到200,以此类推到100.txt的内容为9901到10000。
 8 """
 9 
10 import os
11 
12 
13 # 创建文件夹
14 def create_directory():
15     # os.chdir('E:')                                            # 切换到指定目录
16     path = r'E:pycharmfileexercise'                           # 指定文件根目录
17     file_name = '100txt'                                        # 子目录
18     target_path = os.path.join(path, file_name)                 # 将子目录放在根目录下面
19     if not os.path.isdir(target_path):
20         os.mkdir(target_path)
21     # print(target_path)
22     return target_path
23 
24 
25 # 产生txt文件
26 def create_txt():
27     for i in range(1, 101):
28         # 创建100个txt
29         txt = '{}.txt'.format(str(i))
30         with open(txt, 'w', encoding='utf-8') as f:
31             # 写入内容
32             for j in range(1, 101):
33                 f.write(str(j+(i-1)*100)+'
')
34 
35 
36 if __name__ == '__main__':
37     # 当前工作目录
38     print(os.getcwd())
39     # 文件要保存的目录
40     fpath = create_directory()
41     # 切换到目标目录
42     os.chdir(fpath)
43     # 开始生成txt文件
44     create_txt()
明月装饰了你的窗子,你装饰了他的梦。
原文地址:https://www.cnblogs.com/zkkysqs/p/9147069.html