ホームページ バックエンド開発 Python チュートリアル Python の基本学習コード ファイルと入出力

Python の基本学習コード ファイルと入出力

Dec 29, 2016 pm 05:22 PM
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(&#39;Enter amount of money<must be digit.>:&#39;))
                cancel = raw_input(&#39;Cancel,please press "c"...\n&#39;)
                if cancel == &#39;c&#39;:
                    return False
                else:
                    f = open(&#39;e:\\FamilyAccount.ini&#39;,&#39;w&#39;)
                    cf.write(f)
                    f.close()
        elif enter == &#39;e&#39;:
            return False
        else:
            print &#39;Invalid operation,try again&#39;

import sys
import os
def calc(argument):
    if argument[1] == &#39;+&#39;:
        return int(argument[0]) + int(argument[1])
    elif argument[1] == &#39;*&#39;:
        return int(argument[0]) * int(argument[1])
    elif argument[1] == &#39;-&#39;:
        return int(argument[0]) - int(argument[1])
    elif argument[1] == &#39;**&#39;:
        return int(argument[0]) ** int(argument[1])
    elif argument[1] == &#39;/&#39;:
        return int(argument[0]) / int(argument[1])
#if __name__ == &#39;__main__&#39;:
    if sys.argv[1:][0] == &#39;print&#39;:
        with open(&#39;e:\\txt&#39;,&#39;r&#39;) as f:
            print f.read()
        os.remove(&#39;e:\\txt&#39;)
    else:
        with open(&#39;e:\\txt&#39;,&#39;w&#39;) as f:
            f.write("".join(sys.argv[1:]))
            f.write(&#39;\n&#39;)
            f.write(str(calc(sys.argv[1:])))
            f.write(&#39;\n&#39;)

def func14():
    afile = raw_input(&#39;input file:&#39;)
    bfile = raw_input(&#39;input file:&#39;)
    with open(afile,&#39;r&#39;) as af:
        with open(bfile,&#39;w&#39;) as bf:
            for eachline in afile:
                bf.write(eachline)
        with open(bfile) as bf:
            print bf.read()

import os
def func15():
    file = raw_input(&#39;enter file:&#39;)
    with open(file,&#39;r&#39;) as af:
        with open(&#39;e:\\test.txt&#39;,&#39;w&#39;) 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(&#39;\n&#39;)
                        alist = alist[79:]
                    bf.write("".join(alist))
                else:
                    bf.write(eachline)
                    bf.write(&#39;\n&#39;)
    with open(&#39;e:\\test.txt&#39;,&#39;r&#39;) as bf:
        with open(file,&#39;w&#39;) as af:
            for eachline in bf:
                af.write(eachline)
    os.remove(&#39;e:\\test.txt&#39;)

def createfile():
    file = raw_input(&#39;input filename:&#39;)
    content = raw_input(&#39;input file content:&#39;)
    f = open(file,&#39;a+&#39;)
    f.write(content)
    f.write(&#39;\n&#39;)
    f.close()

def viewfile():
    file = raw_input(&#39;input filename:&#39;)
    strtemp = &#39;&#39;
    f = open(file,&#39;r&#39;)
    for eachline in f:
        strtemp = strtemp + eachline
    return strtemp

def editfile():
    file = raw_input(&#39;input filename:&#39;)
    line = int(raw_input(&#39;input line number:&#39;))
    newline = raw_input(&#39;input new line number:&#39;)
    f = open(file,&#39;r&#39;)
    lines = f.readlines()
    f.close()
    if line > len(lines):
        return False
    lines[line-1] = newline
    f = open(file,&#39;w&#39;)
    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 = &#39;e&#39;
        if commnet == &#39;a&#39;:
            createfile()
        elif commnet == &#39;b&#39;:
            viewfile()
        elif commnet == &#39;c&#39;:
            editfile()
        elif commnet == &#39;d&#39;:
            pass
        elif commnet == &#39;e&#39;:
            break
        else:
            continue
#if __name__ == &#39;__main__&#39;:
#    showmenu()

def func16():
    filename = raw_input(&#39;input file:&#39;)
    filech = raw_input(&#39;input file character:&#39;)
    countnum = 0
    with open(filename,&#39;r&#39;) as f:
        for eachline in f:
            countnum += eachline.count(filech)
    print &#39;character %s is count %d&#39; % (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(&#39;e:\\hello.zip&#39;,&#39;w&#39;) as f:
        f.write(filename)

def func19(dirname):
    with zipfile.ZipFile(&#39;e:\\test.zip&#39;,&#39;w&#39;) 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(&#39;zip file name:&#39;)
    print &#39;size:%.2f&#39; % (float(os.stat(filename).st_size)/1024/1024),"MB"
    f = zipfile.ZipFile(filename,&#39;r&#39;)
    print &#39;filename datetime size compresssize rate&#39;
    for info in f.infolist():
        #t = time.ctime(time.mktime(tuple(list(info.date_time) + [0,0,0])))
        #print &#39;%s\t%s\t%d\t%d\t&#39; % (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)!


このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

LinuxターミナルでPythonバージョンを表示するときに発生する権限の問題を解決する方法は? LinuxターミナルでPythonバージョンを表示するときに発生する権限の問題を解決する方法は? Apr 01, 2025 pm 05:09 PM

LinuxターミナルでPythonバージョンを表示する際の許可の問題の解決策PythonターミナルでPythonバージョンを表示しようとするとき、Pythonを入力してください...

あるデータフレームの列全体を、Python内の異なる構造を持つ別のデータフレームに効率的にコピーする方法は? あるデータフレームの列全体を、Python内の異なる構造を持つ別のデータフレームに効率的にコピーする方法は? Apr 01, 2025 pm 11:15 PM

PythonのPandasライブラリを使用する場合、異なる構造を持つ2つのデータフレーム間で列全体をコピーする方法は一般的な問題です。 2つのデータがあるとします...

プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は? プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は? Apr 02, 2025 am 07:18 AM

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

uvicornは、serving_forever()なしでhttpリクエストをどのように継続的に聞いていますか? uvicornは、serving_forever()なしでhttpリクエストをどのように継続的に聞いていますか? Apr 01, 2025 pm 10:51 PM

UvicornはどのようにしてHTTPリクエストを継続的に聞きますか? Uvicornは、ASGIに基づく軽量のWebサーバーです。そのコア機能の1つは、HTTPリクエストを聞いて続行することです...

文字列を介してオブジェクトを動的に作成し、Pythonでメソッドを呼び出す方法は? 文字列を介してオブジェクトを動的に作成し、Pythonでメソッドを呼び出す方法は? Apr 01, 2025 pm 11:18 PM

Pythonでは、文字列を介してオブジェクトを動的に作成し、そのメソッドを呼び出す方法は?これは一般的なプログラミング要件です。特に構成または実行する必要がある場合は...

人気のあるPythonライブラリとその用途は何ですか? 人気のあるPythonライブラリとその用途は何ですか? Mar 21, 2025 pm 06:46 PM

この記事では、numpy、pandas、matplotlib、scikit-learn、tensorflow、django、flask、and requestsなどの人気のあるPythonライブラリについて説明し、科学的コンピューティング、データ分析、視覚化、機械学習、Web開発、Hの使用について説明します。

中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか? 中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか? Apr 02, 2025 am 07:15 AM

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

See all articles