读写文件 及 输入和输出 知识详解

读写文件

使用的工具:

open(file,     #代表打开(读或者写)哪个文件,
​                       绝对路径/相对路径  
​          mode='r',  #代表打开文件的方式
​                             读/写的方式,文本/二进制
​          buffering=-1,  #缓存
​          encoding=None,  #编码:UTF-8,GBK
​          errors=None,   #错误处理:strict
​          newline=None,  #新起一行
​          closefd=True,  #关闭文件描述符(Linux用的较多)
 ========= ===============================================================
    Character Meaning

--------- ---------------------------------------------------------------

​    'r'       open for reading (default)
​              打开方式默认为读
​    'w'       open for writing, truncating the file first
​              以写的方式打开,先删除文件,然后建立空文件
​    'x'       create a new file and open it for writing
​              创建新文件并以写的方式打开
​    'a'       open for writing, appending to the end of the file if it exists
​              以写的方式打开,如果文件存在将追加到文件的末尾
​    'b'       binary mode
​              二进制模式
​    't'       text mode (default)
​              默认为文本模式
​    '+'       open a disk file for updating (reading and writing)
​              打开磁盘文件并更新(读写)
​  ========= ===============================================================

读写文件练习:

读写一个文档:

file_obj = open("review", mode="rt", encoding="utf-8")
data = file_obj.read()   #读review这个文件
file_obj_w = open("tushuguan.txt", mode="wt", encoding="utf-8")
file_obj_w.write(data)   #创建 tushuguan.txt 文件,并将 revew 文件内容写进该文件
file_obj.close()
file_obj_w.close()

运行上边程序会新建一个“tushuguan.txt”文件,并将"review"文件内容复制到“tushuguan.txt”文件中。

读写一张照片:

file_obj = open("python.jpg", mode="rb")
data = file_obj.read()
file_obj_w = open("python_cp.jpg", mode="wb")
file_obj_w.write(data)
file_obj.close()
file_obj_w.close()

运行完成后会将照片"python.jpg"复制到新创建的"python_cp.jpg"文件中

读写文件的其他应用:

with open("huyi.txt", mode="a", encoding="utf-8") as file_obj:  #将内容追加到文件末尾
    file_obj.write("我学习关于云计算网络安全的知识")  #追加一行内容
    file_obj.writelines(["\n目前正在学习python语言", "\n已经学习了hcia和rhcsa课程"])   #追加多行内容

with open("review", encoding="utf-8") as file_obj:
    # data = file_obj.read(10)    #指定读取字符的个数
    data = file_obj.readlines(50)    #读取到满足字符的所有行的内容
    print(data)

输入和输出

输入:

data = input("请输入:")
print(data, type(data))    #执行后输入任何内容,数据类型总为str

格式化输出:

name = "小明"
age = 20
#格式:My name is xxx, My age is 20
print("My name is ", name, "My age is ", age)
print("My name is %s, My age is %d" % (name, age))
print(f"My name is {name}, My age is {age}")
#format函数
print("My name is {}, My age is {}".format(name, age))
print("My name is {0}, My age is {1}".format(name, age))
print("My name is {name}, My age is {age}".format(name=name, age=age))

输出结果为:
在这里插入图片描述

打印表格练习:

print("{0:^5}{1:^15}{2:^15}".format("姓名", "联系方式", "学校"))
print("{0:*<5}{1:*<15}{2:*<15}".format("张三", "11111111111", "西安石油大学"))
print("{0:|^5}{1:|^15}{2:|^15}".format("里斯", "22222222222", "西安交通大学"))
print("{0:->5}{1:->15}{2:->15}".format("王五", "33333333333", "西安科技大学"))

另一种写法:

print(f"{'姓名':^5}{'联系方式':^15}{'学校':^30}")
print(F"{'张三':*<5}{'11111111111':*<15}{'西安石油大学':*<15}")
print(f"{'里斯':*<5}{'22222222222':*<15}{'西安交通大学':*<15}")
print(F"{'王五':*<5}{'33333333333':*<15}{'西安科技大学':*<15}")

符号说明:
<:左对齐
^:居中对齐
>:右对齐
*:填充空白字符(也可以填充其他符号)

输出结果为:
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中进行文件读写操作需要使用fstream类,它包含在<fstream>头文件中。 文件输入输出流分为两种:ifstream(输入文件流)和ofstream(输出文件流)。它们都是继承自基类fstream。 文件输入输出操作主要有以下几个步骤: 1. 打开文件:使用open()函数打开文件,打开方式可以是读入(ios::in)、写出(ios::out)、追加(ios::app)等方式。 2. 读写文件:使用>>和<<运算符进行文件读写操作。 3. 关闭文件:使用close()函数关闭文件。 示例代码如下: ```c++ #include <iostream> #include <fstream> using namespace std; int main() { // 打开文件 ofstream fout("output.txt", ios::out); ifstream fin("input.txt", ios::in); // 写入文件 fout << "Hello, world!\n"; fout << "This is a test file.\n"; // 读取文件 string line; while (getline(fin, line)) { cout << line << endl; } // 关闭文件 fout.close(); fin.close(); return 0; } ``` 上述代码中,我们打开了一个输出文件流`ofstream`,并将其命名为`fout`,然后使用`fout`的`<<`运算符向文件中写入了两行文本。 接着,我们打开了一个输入文件流`ifstream`,并将其命名为`fin`,使用`getline()`函数读取了文件中的每一行,并在控制台输出。 最后,我们使用`close()`函数关闭了文件流。 需要注意的是,在进行文件读写操作时,我们需要保证文件存在并且有读写权限。如果文件不存在,则可以使用`ofstream`对象的`open()`函数来创建文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值