如何用PYTHON读取文件

2025-11-02 16:09:32

1、新建一个PY文档,并且新建一个文本作为示范,放在同一个类目底下。

如何用PYTHON读取文件

如何用PYTHON读取文件

2、abc_file = open("abc.txt", "r")

abc_file.close()

基本的OPEN和CLOSE,打开并且关闭文件。

如何用PYTHON读取文件

3、abc_file = open("abc.txt", "r")

print(abc_file.readable())

abc_file.close()

如果我们设置为R模式,就是可读取的。

如何用PYTHON读取文件

4、abc_file = open("abc.txt", "w")

print(abc_file.readable())

abc_file.close()

如果设置为W模式,那么只是写模式,不是读取模式。

如何用PYTHON读取文件

5、abc_file = open("abc.txt", "r")

print(abc_file.read())

abc_file.close()

直接用READ()可以读取所有的数据。

如何用PYTHON读取文件

6、abc_file = open("abc.txt", "r")

print(abc_file.readline())

abc_file.close()

readline()是读取第一行。

如何用PYTHON读取文件

7、abc_file = open("abc.txt", "r")

print(abc_file.readline())

print(abc_file.readline())

abc_file.close()

多个readline()就是读取多行数据。

如何用PYTHON读取文件

8、abc_file = open("abc.txt", "r")

print(abc_file.readlines())

abc_file.close()

readlines()就是读取所有行的数据。

如何用PYTHON读取文件

9、abc_file = open("abc.txt", "r")

print(abc_file.readlines()[2])

abc_file.close()

abc_file = open("abc.txt", "r")

print(abc_file.readlines()[0])

abc_file.close()

我们可以指定具体读取哪一行。

如何用PYTHON读取文件

10、abc_file = open("abc.txt", "r")

for abc in abc_file.readlines():

    print(abc)

abc_file.close()

用FOR LOOPS也是可以读取所有的数据。

如何用PYTHON读取文件

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢