【Python自学笔记】EX15-EX17 对文件的操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_24994943/article/details/81939093
# ex15
# 打开文件并读取文件内容

from sys import argv
script, filename = argv
txt = open(filename) # 根据文件名打开文件

print(f"Here's your file {filename}:")
print(txt.read()) # 读取该文件中的文本并输出

print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())


# ex16
# 文件的写入
from sys import argv
script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).") # 输出CTRL-C指令,可中断执行
print("If you do want that, hit RETURN.")

input("?")

print("Opening the file...")
target = open(filename, 'w') # 以write的模式打开文件

print("Truncating the file. Goodbye!")
target.truncate() # 此步非必须,若无此函数,以w模式打开文件,则系统首先会自动将文件清空

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

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

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

# 第一种写入三行文字的方式
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

# 以string的方式写入三行文字
#target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")

# 以format的方式写入三行文字
# 其一
#target.write(f"{line1}\n{line2}\n{line3}\n")
# 其二
#formatter = "{}\n{}\n{}\n"
#target.write(formatter.format(line1, line2, line3))

print("And finally, we close it.")
target.close()


# ex17
# 文件的拷贝
from sys import argv
from os.path import exists

script, from_file, to_file = argv


print(f"Copying from {from_file} to {to_file}")

in_file = open(from_file)
indata = in_file.read()

print(f"The input file is {len(indata)} bytes long") # len(indata)获取indata的长度

print(f"Dose the output file exist? {exists(to_file)}") # exists(to_file)检测文件是否存在,存在返回True
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()

out_file = open(to_file,'w')
out_file.write(indata)

print("Alright, all done.")

out_file.close()
in_file.close()

# 用一行来实现上述功能,即文件的copy(此时打开的两个文件是否会被python自动关闭?)
# open(to_file,'w').write(open(from_file).read())

猜你喜欢

转载自blog.csdn.net/sinat_24994943/article/details/81939093
今日推荐