python 如何新建一个新的File?

python 如何新建一个新的File?谢谢啦!
2024-07-17 21:07:27
推荐回答(4个)
回答1:

#python 

f=open('f.txt','w')    # r只读,w可写,a追加

for i in range(0,10):f.write(str(i)+'\n')

例子:

#!/usr/bin/python

#coding=utf-8

import os

import time

import sys

f=open('a.txt','a')

f.write(os.popen('netstat -nltp | grep 22').read())

f.close()

扩展资料:

关于上述创建文件,文件内容追加

#python

import random

f=open('f.txt','a')

for i in range(0,10):f.write(str(random.randint(0,9)))
.  .  .

f.write('\n')

f.close()

或者

#python

import rando

f=open('f.txt','a')

for i in range(0,10):

for i in range(0,10):f.write(str(random.randint(0,9)))  

f.write('\n')     

f.close()

回答2:

例如如果你想在c盘下建一个a.txt的文本文档,你可以用下面的python语句
f = file("c:\\a.txt", "w")
f.close()

回答3:

直接用
f = file('路径+文件名','w')如果只是创建而无需操作就省略掉那个 w

回答4:

new_path_filename包含文件路径和文件名,例如:
new_path_filename = r'c:\windows\system32\ceshi'
new_path_filename = r'\var\log\test'

在Linux下可以考虑使用系统的touch命令:
os.system(r'touch %s' % new_path_filename)

在任何系统下都可以使用Python自己的函数:
f = open(new_path_filename, 'w')
f.close()
如果文件不存在,就会新建立一个文件,如果直接向内部写内容,可以在
f.close()之前执行写入函数:
f.write('aa bb cc dd ...\n')