亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Python學習16:讀寫文件

標簽:
Python

# -*- coding: utf-8 -*-

from sys import argv  # 从sys模块导入argv函数,

#「argv」是「argument variable」参数变量的简写形式。一般在命令行调用的时候由系统传递给程序。

# 一般在命令行调用的时候由系统传递给程序。

script, filename = argv # 利用argv函数,把 argv 中的东西解包,将所有的参数依次赋予左边的变量名

print "We're going to erase %r." % filename # 打印文件名参数

print "If you don't want that, hit CTRL-C (^C)." # 提示输入CTRL+C就退出程序

print "If you do want that, hit RETURN." 

print

print "Here is the original file: "

print

txt = open(filename) # 使用open函数打开文件,并把内容存到txt变量中

print txt.read() # 读取txt的内容并打印出来,这一块是为了读取未清除文件内容并写入其他内容之前的内容

raw_input("?")

print "Opening the file..."

target = open(filename, 'w') # 以写模式打开文件

print "Truncating the file. Goodbye!"

target.truncate() # 用truncate函数清除文件内容

print "Now I'm going to ask you for three lines."

print

#line1 = raw_input("Line 1: ") # 写入三行内容,保存到line1,line2和line3的变量中

txt1 = open(filename, 'w')

txt1.write ('This is a test.\nReally, it is.')

txt1.close()

print

print "I'm going to write these to the file."

print

target.write(line2) # 使用write函数把line1变量中

target.write("\n") # 使用write函数写入一个换行符

target.write(line2) #使用write函数把line2变量中

target.write("\n") # 使用write函数写入一个换行符

target.write(line3) #使用write函数把line3变量中

target.write("\n") # 使用write函数写入一个换行符

print

print "And finally, we close it."

target.close() # 关闭文件

filename1 = raw_input("input a filename: ")

filename1_open = open(filename1) # 打开文件

print "Here is the new file content: "

print

print filename1_open.read() # 读取新的文件内容

print "close opened file..."

filename1_open.close() # 关闭文件

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消