现在开始学习文件了,其实前面的学习中还有不少遗漏的地方,以后我会继续改进,加油
文章目录
1.从文件中读取数据
1.1读取整个文件
首先创建一个文本文档,内容自定义,我的内容如下:
hello python
how are you?
you are so easy
然后通过代码打开它
with open('hello.txt') as file_object:
text=file_object.read()
print(text)
--------------------------
hello python
how are you?
you are so easy
你可能会看到输出的数据有多余的空行,如果有,则参照如下代码
with open('hello.txt') as file_object:
text=file_object.read()
print(text.rstrip())
----------------
hello python
how are you?
you are so easy
1.2文件路径
如果你要打开的文件不在当前代码所在的文件夹,你需要明确它的路径
1.2.1绝对路径
file_path=r'C:\Users\dell\Desktop\hello.txt'
with open(file_path) as file_object:
text=file_object.read()
print(text.rstrip())
--------------------
hello python
how are you?
you are so easy
记得绝对路径单引号前加r第一次我没加,然后报错
1.2.2相对路径
with open('text_files\hello.txt') as file_object:
text=file_object.read()
print(text.rstrip())
-------------------
hello python
how are you?
you are so easy
1.3逐行读取
with open('text_files\hello.txt') as file_object:
for line in file_object:
print(line)
-------------------
hello python,
how are you?
you are so easy.
去掉多余空行
with open('text_files\hello.txt') as file_object:
for line in file_object:
print(line.rstrip())
-------------------
hello python,
how are you?
you are so easy.
1.4创建一个包含文件各行内容的列表
with open('text_files\hello.txt') as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
print("读取列表中的元素")
print(lines[1])
-------------------
hello python,
how are you?
you are so easy.
读取列表中的元素
how are you?
1.5使用文件内容
with open('text_files\hello.txt') as file_object:
lines=file_object.readlines()
hello_string=' '
for line in lines:
hello_string+=line.rstrip()
print(hello_string)
print(len(hello_string))
-------------------
hello python,how are you?you are so easy.
42
2.写入文件
2.1写入空文件
with open('text_files\hello.txt','w') as file_object:
file_object.write('I love python.')
with open('text_files\hello.txt') as file_object:
text=file_object.read()
print(text)
------------------
I love python.
2.2写入多行
with open('text_files\hello.txt','w') as file_object:
file_object.write('I love python.')
file_object.write('I love hadoop.')
file_object.write('I love r.')
with open('text_files\hello.txt') as file_object:
text=file_object.read()
print(text.title())
----------------
I Love Python.I Love Hadoop.I Love R.
你可以加入换行符让每个字符串独占一行
这样写入会直接覆盖原有文件!!!谨慎操作
如果你只是想在文本的内容后面添加内容,则使用以下方法
with open('text_files\hello.txt','a') as file_object:
file_object.write('i am here.')
file_object.write('I get you.')
file_object.write('go for it.')
with open('text_files\hello.txt') as file_object:
text=file_object.read()
print(text.title())
----------------
I Love Python.I Love Hadoop.I Love R.I Am Here.I Get You.Go For It.