python新建txt文件
1. 怎樣編寫程序在當前試題目錄下創建一個文本文件用python
又編寫程序在當前的試題的目錄下創建一個文本文件呃,用這個還是可以的。
2. 如何用Python創建一個TXT文檔
f=open("ab.txt",'a'),沒有就創建
3. 用python怎麼創建一個文件
withopen('test.txt','w')asf:
f.write('helloworld')#創建文件test.txt並寫入helloworld
4. Python創建txt時報錯IOError:[Errno 22]invalid mode('w')
1.讀寫操作i
#寫入襲方式會將原文本刪除,重新寫入,
#若文件不存在,即新建test.txt
File = open("test.txt",'w+')
2讀寫操作ii
#寫入方式會將原文本刪除,重新寫入,
#若文件不存在,報錯
File = open("test.txt",'r+')
3.讀寫操作iii
#這種寫入是在原文件的基礎上,繼續寫入
#可讀可寫
File = open("test.txt",'a+')
5. python變成問題,建立txt文件寫入語句但不顯示
這是一個追加到文件的例子
s='HelloPython! '
withopen('test1.txt','a')asfw:
fw.write(s)
6. python對文件寫入, 新建的文件找不到
你的文件路徑有問題,反斜杠會被認為是轉義字元有兩種修改方法:
1.反斜杠改成雙反斜杠f=file('C:\\Users\\Administrator\\Desktop\\111.txt','a')
2.使用raw string,也就是在string'前面加r,告訴python不需要轉義f=file(r'C:\Users\Administrator\Desktop\111.txt','a')
完整代碼如下:
f = file(r'C:\Users\Administrator\Desktop\111.txt', 'a')
data = 'wo'
f.write(data)
f.close()
s = file(r'C:\Users\Administrator\Desktop\111.txt')
print s.read()
s.close()
7. 我明明在桌面創建了一個txt文件,可python就是說找不到呢
你把你的這行改成這樣試下:
fin=open('C://Users//dell//Desktop//words.txt') #加多一個'/'符。
或
fin=open('C:\\Users\\dell\\Desktop\\words.txt')
註:建議以後提問題盡可能闡述得更詳細些,讓回答者能把問題研究得透點。
8. 用python編寫程序5.新建一個文本文件zen.txt, 文件內容為「Python之禪」的部分內容,具體如下
strList=[]
line=0
f=open("zen.txt","r")
forvinf.readlines():
arr=v.split()
strList.extend(arr)
line+=1
f.close()
print('行數:',line)
print('單詞內:容',len(strList))
#行數:4
#單詞:20
9. python 如何新建一個新的File
#python
f=open('f.txt','w') # r只讀,w可寫,a追加
for i in range(0,10):f.write(str(i)+' ')
例子:
#!/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()
(9)python新建txt文件擴展閱讀:
關於上述創建文件專,文件內容屬追加
#python
import random
f=open('f.txt','a')
for i in range(0,10):f.write(str(random.randint(0,9)))
. . .
f.write(' ')
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('
')
f.close()
10. python創建根據時間的txt文件
importtime
tm=time.strftime("%Y-%m-%d%X",time.localtime())
timeslog=tm+r'.txt'
sp=open(timeslog,'w')
sp.close()
代碼沒問題
但是Windows系統中 文件名不能包含下列任何字元:
/ : * ? 」(英文右引號) < > |
所以考慮下修改下時間格式