python file 文件相关知识

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34579060/article/details/87371101
# study python 2019-02-15
"""
    从文件中读取数据:
        文本文件可存储的数据量多得难以置信, 天气数据、交通数据、社会经济数据、文学作品等。
    每当需要分析或者修改存储在文件的信息时,读取文件很有用, 对于数据分析的程序来说尤其如此。

"""
abc_path = r'file\abc.txt'

# 读取整个文件
with open(abc_path, encoding='utf-8') as file_object:
    contents = file_object.read()
    print("=============打印文件全部内容======================")
    print(contents)
    print("=============打印文件内容长度======================")
    print(len(contents))
    print("=============打印文件内容,去除末尾空行======================")
    print(contents.strip())
'''
   在这个程序中第一行做了大量的工作, open('abc.txt')函数接收要打开的文件名称, 
   使用read()方法读取整个文件的内容,然后将其存储在一个字符串中contents,使用print函数将其打印出来
'''

left_blank_content = "    alice love read book "
print("=============去除左边空白行======================")
print(left_blank_content)
print(left_blank_content.lstrip())
print()

right_blank_content = "alice is a very beautiful girl       "
print("=============去除右边空白行======================")
print(right_blank_content)
print(right_blank_content.rstrip())
print()

blank_content = "      alice is a very beautiful girl       "
print("=============去除两边空白行======================")
print(blank_content)
print(right_blank_content.strip())


'''
  当你将类似abc.txt 这样简单文件名传递给函数open()时, python将在当前执行的文件(即是.py程序文件)所在的目录中查找文件
  也可以指定具体盘符路径下的txt文件.
  通过使用绝对路径,可以读取系统内任何地方的文件, 由于反斜杠在python中被视为转移标记,为在windows中万无一失,应
  以原始字符串的方式指定路径,即在开头的单引号前加上r
'''
print("====================盘符下指定的txt文件=================================")
area_no_path = r'D:\abc.txt'
with open(area_no_path) as file_object:
    contents = file_object.read()
    print(contents)


print("====================逐行读取=================================")
# 逐行读取
with open(area_no_path) as file_object:
    for line in file_object:
        print(line.strip())  # 在这个文件中, 每行的末尾都有一个看不见的换行符, 而print()语句也会加上一个换行符

print("====================逐行读取时过滤=================================")
with open(area_no_path) as file_object:
    for line in file_object:
        if line.split(" ")[0] == '810200':
            print(line)


print("====================文本读取,文本没有汉字=================================")
'''
    文本读取时
        1. 没有存在汉字,此时也没有指定编码格式
            读取结果没有问题
        2. 存在汉字
           出现乱码,但并没有出现之前的错误
     指定编码后: 可以解决乱码问题      
'''
text_path = r'file\test.txt'
with open(text_path, encoding='utf-8') as file_object:
    contents = file_object.read()
    print(contents)


# 创建一个包含文件各行内容的列表
'''
    使用关键字with时, open()返回的文件对象只在with代码块内可用,如果要在代码块外可用,可以将
    代码文本内各行读取到一个列表中,以此在延后的过程中使用
'''

print("====================文本读取到列表中=================================")
with open(abc_path, encoding='utf-8') as file_object:
    lines = file_object.readlines()
    # readlines() 从文件中读取每一行,并将其存储在一个列表中


line_str = ''
for line in lines:
    line_str += line.strip()
print(line_str)
print(line_str.__len__())
print(len(line_str))

'''
   读取文本文件时,Python将其中所有的文本都解读为字符串。如果你读取的是数字,并且要将其作为
   数值使用,就必须使用函数int()将其转换为整数,或者使用函数float()将其转换成浮点数
'''

# 读取一个超大文件时,我们可以截取前一部分的进行展示,以免终端为显示全部数据而不断的翻滚:
print("====================写入文本=================================")
filename = r'file\number.txt'
with open(filename, mode="w") as file_object:
    file_object.write("hello file, i will call you ")

'''
  如果你写入的文件不存在,python会创建指定的文件, 如果指定的文件存在, 那么以 mode = 'w' 时就要小心,
  python将在返回文件对象之前清空该文件.
'''
print("==============mode = 'w' 写入文本============================")
with open(filename, mode="w") as file_object:
    print("以mode = w 打开文本,如果文件存在将会在返回文件对象之前清空文本'")

'''
   注意: python只能讲字符串写入文本文件。要将数值数据存储到文件文件中,必须使用str()将其转换成字符串格式
'''
age = 20
with open(filename, mode="w") as file_object:
    file_object.write(str(age))

print("==================写入多行,指定编码格式============================")
with open(filename, mode="w", encoding='utf-8') as file_object:
    file_object.write("I love english \n")
    file_object.write("I love math \n")
    file_object.write("I love china \n")
    file_object.write("我爱中华 \n")
    file_object.write("我爱读书 \n")
    file_object.write("我爱古代文学\n")

print("==================追加文件============================")
with open(filename, mode='a', encoding='utf-8') as file_object:
    file_object.write("追加文本成功 \n")

with open(filename, encoding='utf-8') as file_object:
    contents = file_object.readlines()
    message = contents[:3]
    message.append("...")
    print(message)

name = input("请输入您的姓名")
file_path = 'file\test.txt'
with open(file_path, mode='w', encoding='utf-8') as file_object:
    file_object.write(name)
    print("文件录入成功")

猜你喜欢

转载自blog.csdn.net/qq_34579060/article/details/87371101