Python程序教程

您现在的位置是:首页 >  Python

当前栏目

python对文件的操作

python,文件,操作
2025-03-28 09:01:03 时间

大家好,又见面了,我是你们的朋友全栈君。

一.python2

1.将字符串写入文件

# -*- coding: utf-8 -*-

data_str = "Hello world!!!"
file_object = open('D:/test.txt', 'w')
file_object.write(data_str)
file_object.close()

2.以追加的方式写入文件

# -*- coding: utf-8 -*-

data_list = ["我是第一行","我是第二行","我是第三行","我是第四行"]
file_object = file("D:/text.txt", "a+")
for i in data_list:
    file_object.write(i)
file_object.close()

3.清空文件内容

# -*- coding: utf-8 -*-

file_object = file("D:/test.json", "a+")  # 以追加的方式
file_object.truncate()
file_object.close()

4.删除文件最后一个字符

# -*- coding: utf-8 -*-

import os

# 不要是中文字符,不然会出现乱码
file_object = file("D:/test.txt", "a+")
file_object.seek(-1, os.SEEK_END)
file_object.truncate()
file_object.close()

5.以固定的编码格式打开文件并读写

# -*- coding: utf-8 -*-

import codecs
file_path = "markov30_for_xs80.txt"
file_object = codecs.open(file_path, 'r', encoding='utf-16 LE')

for index, line in enumerate(file_object):
    print line

二.python3

1.将字符串写入文件

data_str = "哈哈"
file_object = open("test.txt", 'w', encoding="utf8")
file_object.write(data_str)
file_object.close()

2.以追加的方式写入文件

str_list = ["我是第一行", "我是第二行", "我是第三行", "我是第四行"]
file_writer = open("test.txt", "a+", encoding="utf8")
for i in str_list:
    file_writer.write(i)
file_writer.close()

3.清空文件内容

file_writer = open("test.txt", "rb+")
file_writer.truncate()
file_writer.close()

4.删除文件最后一个字符

# 不要是中文字符,不然会出现乱码

import os

file_object = open("test.txt", "rb+")
file_object.seek(-1, os.SEEK_END)
file_object.truncate()
file_object.close()

5.按行读取 txt 等文本文件

file_object = open("C:/abc.txt", "r+")
line = file_object.readline()

while line:
    line = file_object.readline()
    if line.strip() == "":
        continue
    one_data = line.strip().replace("	", ",").replace("	", ",").split(",")
    print(one_data)

file_object.close()

6.直接读取 txt 等文本文件

file_object = open("C:/abc.txt", "r+")
file_data_str = file_object.read()
file_object.close()

7.直接将字符串写入文件

data_str = "abcdefg"
txt_file = open("C:/abc.txt", 'w')
txt_file.write(data_str)
txt_file.close()

三.文件夹操作

1.创立文件夹

"""
创建文件夹
"""
import os


def create_dir(path):
    if_exist = os.path.exists(path.strip().rstrip("\\"))
    if not if_exist:
        os.mkdir(path)
        print(path + ' 创建成功')
        return True
    else:
        print(path + ' 目录已存在')
        return False


create_dir("D:/test")

2.循环创建多层文件夹

"""
循环建立多层文件夹
"""
import os


def create_dir(path):
    if_exist = os.path.exists(path.strip().rstrip("\\"))
    if not if_exist:
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        print(path + ' 目录已存在')
        return False


create_dir("D:/test/test/test")

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/141586.html原文链接:https://javaforall.cn