Python 기본 학습 코드 파일 및 입력 및 출력
import os ls = os.linesep def func1(): filename = raw_input('enter file name:') f = open(filename,'w') while True: alline = raw_input("enter a line ('.' to quit):") if alline != '.': f.write("%s%s"%(alline,ls)) else: break f.close() def func2(): f = open('e:\\thefile.txt','w+') print f.tell() f.write('the line 1\n') print f.tell() f.write('the line 2\n') print f.tell() f.seek(-12,1) print f.readline() print f.tell() f.seek(0,0) print f.readline() print f.tell() f.close() import sys import os def func3(): print 'you are',len(sys.argv),'arguments' print 'there are',str(sys.argv) def func4(): for tmpdir in ('e:\\','d:\\'): if os.path.isdir(tmpdir): break else: print 'no directory available' tmpdir = '' if tmpdir: os.chdir(tmpdir) cwd = os.getcwd() print 'current directory',cwd print 'create example directory' #os.mkdir('example') #os.chdir('example') cwd = os.getcwd() print 'new directory',cwd print 'directory list' os.listdir(cwd) print 'create test file' f = open('test','w') f.write('test\n') f.write('test\n') f.close() print 'update directory list' print os.listdir(cwd) print 'rename test to filetest' #os.rename('test','filetest') print 'update directory list' print os.listdir(cwd) path = os.path.join(cwd,os.listdir(cwd)[0]) print 'full file pathname' print path print 'pathname,basename' print os.path.split(path) print 'filename,extension' print os.path.basename(path) print os.path.splitext(os.path.basename(path)) print 'display file contents' f = open('test','r') for eachline in f: print eachline f.close() print 'delete test file' os.remove(path) print 'update directory list' print os.listdir(cwd) os.chdir(os.pardir) print 'delete test directory' os.rmdir('example') print 'done' def func5(): print os.path.expanduser("~") def func6(): filename = raw_input('input file:') f = open(filename,'r') for eachline in f: if not eachline.strip().startswith('#'): print eachline def func7(): filename = raw_input('input file:') f = open(filename,'r') for eachline in f: if not '#' in eachline[1:]: print eachline f.close() def func8(): filename = raw_input('input file:') line = int(raw_input('input line number:')) f = open(filename,'r') for eachline in f: if line: print eachline line -= 1 else: break def func9(): filename = raw_input('input file:') lines = open(filename,'r').readlines() return len(lines) import os def func10(): ls = os.linesep with open('e:\\tmp.txt','a+') as f: for i in range(100): f.write("%s%s"%(i,ls)) with open('e:\\tmp.txt','r') as f: num = 1 for eachline in f: if num % 26 != 0: print eachline num += 1 else: go = raw_input('continue,press c to quit') num += 1 if go == 'c': break def func11(file1,file2): alines = open(file1,'r') blines = open(file2,'r') row = 0 for (aline,bline) in zip(alines,blines): row += 1 if aline == bline: pass else: col = 0 print row for (a,b) in zip(aline,bline): if a == b: col += 1 else: print col alines.close() blines.close() from ConfigParser import ConfigParser def func12(): cp = ConfigParser() #print os.path.join('C:\\Windows\\','win.ini') cp.read(os.path.join('C:\\Windows\\','win.ini')) for section in cp.sections(): #print cp.items(section) for key in cp.options(section): print '[%s]-%s=%s'%(section,key,cp.get(section,key)) cp.add_section('name') cp.set('name','test',25) f = open(os.path.join("e:\\","test.txt"),'a') cp.write(f) f.close() def func13(): prompt = """ (S)avings (C)heck (F)inancialmarket (D)eposit (E)xit enter your choice:""" function = """ (s)avings (d)raw (b)orrow (l)oan enter your choice:""" account = {'s':'Savings','c':'Check','f':'Financial','d':'Deposit'} fun = {'s':'savings','d':'draw','b':'borrow','l':'loan'} cf = ConfigParser() cf.read('e:\\FamilyAccount.ini') enter = raw_input(prompt).strip().lower()[0] while True: if enter in 'scfd': print 'welcome %s bussness' % account[enter].lower() section = account[enter] select = raw_input(fun).strip()[0].lower() if select in 'sdbl': print 'welcome %s bussness' % fun[select] key = fun[select] mokey = int(raw_input('Enter amount of money<must be digit.>:')) cancel = raw_input('Cancel,please press "c"...\n') if cancel == 'c': return False else: f = open('e:\\FamilyAccount.ini','w') cf.write(f) f.close() elif enter == 'e': return False else: print 'Invalid operation,try again' import sys import os def calc(argument): if argument[1] == '+': return int(argument[0]) + int(argument[1]) elif argument[1] == '*': return int(argument[0]) * int(argument[1]) elif argument[1] == '-': return int(argument[0]) - int(argument[1]) elif argument[1] == '**': return int(argument[0]) ** int(argument[1]) elif argument[1] == '/': return int(argument[0]) / int(argument[1]) #if __name__ == '__main__': if sys.argv[1:][0] == 'print': with open('e:\\txt','r') as f: print f.read() os.remove('e:\\txt') else: with open('e:\\txt','w') as f: f.write("".join(sys.argv[1:])) f.write('\n') f.write(str(calc(sys.argv[1:]))) f.write('\n') def func14(): afile = raw_input('input file:') bfile = raw_input('input file:') with open(afile,'r') as af: with open(bfile,'w') as bf: for eachline in afile: bf.write(eachline) with open(bfile) as bf: print bf.read() import os def func15(): file = raw_input('enter file:') with open(file,'r') as af: with open('e:\\test.txt','w') as bf: for eachline in af: if len(eachline) > 80: alist = list(eachline) count = len(alist) / 80 for i in range(count): bf.write("".join(alist[:79])) bf.write('\n') alist = alist[79:] bf.write("".join(alist)) else: bf.write(eachline) bf.write('\n') with open('e:\\test.txt','r') as bf: with open(file,'w') as af: for eachline in bf: af.write(eachline) os.remove('e:\\test.txt') def createfile(): file = raw_input('input filename:') content = raw_input('input file content:') f = open(file,'a+') f.write(content) f.write('\n') f.close() def viewfile(): file = raw_input('input filename:') strtemp = '' f = open(file,'r') for eachline in f: strtemp = strtemp + eachline return strtemp def editfile(): file = raw_input('input filename:') line = int(raw_input('input line number:')) newline = raw_input('input new line number:') f = open(file,'r') lines = f.readlines() f.close() if line > len(lines): return False lines[line-1] = newline f = open(file,'w') f.writelines(lines) f.close() def showmenu(): prompt = """ a)创建文件(提示输入文件名和任意行的文本输入) b)显示文件(把文件的内容显示到屏幕) c)编辑文件(提示输入要修改的行,然后让用户进行修改) d)保存文件 e)退出 请输入操作选项(a、b、c、d、e):""" while True: try: commnet = raw_input(prompt).strip()[0].lower() except(KeyboardInterrupt,EOFError): commnet = 'e' if commnet == 'a': createfile() elif commnet == 'b': viewfile() elif commnet == 'c': editfile() elif commnet == 'd': pass elif commnet == 'e': break else: continue #if __name__ == '__main__': # showmenu() def func16(): filename = raw_input('input file:') filech = raw_input('input file character:') countnum = 0 with open(filename,'r') as f: for eachline in f: countnum += eachline.count(filech) print 'character %s is count %d' % (filech,countnum) import random def func17(ch,countnum,length): firstlength = 0 num = [] while firstlength - countnum: chara = random.choice(xrange(255)) if ch == chara: continue else: num.append(chara) firstlength -= 1 for i in range(countnum): num.append(ch) newnum = [] while length: i = int(random.random() * length) newnum.append(num[i]) del num[i] length -= 1 return newnum import zipfile def func18(filename): with zipfile.ZipFile('e:\\hello.zip','w') as f: f.write(filename) def func19(dirname): with zipfile.ZipFile('e:\\test.zip','w') as f: for root,dirs,files in os.walk(dirname): f.write(root) for file in files: f.write(os.path.join(root,file)) import time def func20(): filename = raw_input('zip file name:') print 'size:%.2f' % (float(os.stat(filename).st_size)/1024/1024),"MB" f = zipfile.ZipFile(filename,'r') print 'filename datetime size compresssize rate' for info in f.infolist(): #t = time.ctime(time.mktime(tuple(list(info.date_time) + [0,0,0]))) #print '%s\t%s\t%d\t%d\t' % (info.filename,t,info.file_size, # info.compress_size) print info.filename,info.file_size,info.compress_size f.close()
以上就是Python基础学习代码之文件和输入输出的内容,更多相关内容请关注PHP中文网(www.php.cn)!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...
