好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python3文件操作相关的实力分享

文件操作是我们日常在使用python的时候经常会用到的,下面这篇文章主要给大家介绍了关于Python3中简单的文件操作及两个简单小实例的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。

def main():
 input = open("Test.txt","w")
 input.write("SherlockBlaze")
 input.write("\t is the most handsome guy!\n")
 input.close()
 
main() 
import os.path
is os.paht.isfile("Test.txt"):
 print("Test.txt exists")
else:
 print("Test.txt doesn't exists") 
def main():
 filename = input("Enter a filename: ").strip()
 infile = open(filename,"r")
 counts = 26 * [0]
 for line in infile:
 countLetters(line.lower(),counts)
 for i in range(len(counts)):
 if counts[i] != 0:
 print(chr(ord('a') + i) + "appears " + str(counts[i])
 + (" time" if counts[i] == 1 else " times"))
 infile.close()
def countLetters(line,counts):
 for ch in line:
 if ch.isalpha():
 counts[ord(ch) - ord('a')] += 1
main() 
import sys
import urllib
import urllib.request
import os.path
def download(url,num_retries = 2):
 print ('Downloading:',url)
 try:
 html = urllib.request.urlopen(url).read()
 except urllib.URLError as e:
 print ('Download error:',e.reason)
 html = None
 if num_retries > 0:
 if hasattr(e,'code') and 500 <= e.code <600:
 return download(url,num_retries-1)
 return html
def main():
 url = input("Enter a url:\n").strip()
 f2 = input("Enter a target file:\n").strip()
 if os.path.isfile(f2):
 print(f2 + " already exists")
 sys.exit()
 html = download(url)
 target = open(f2,"w")
 content = html.decode(encoding="utf-8")
 target.write(content)
 target.close()
main() 

比如我输入网址 http://HdhCmsTestgame2.cn/,在输入目的文件:game2.txt。即可进行下载并把对应html输入到当前工作目录的game2.txt文件中。

以上就是Python3文件操作相关的实力分享的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Python3文件操作相关的实力分享的详细内容...

  阅读:45次