python对文件的操作

python对文件的操作一.python21.将字符串写入文件#-*-coding:utf-8-*-data_str=”Helloworld!!!”file_object=open(‘D:/test.txt’,’w’)file_object.write(data_str)file_object.close()2.以追加的方式写入文件#-*-coding:utf-8…

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

一.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.net/141586.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ffmpeg安装及使用教程「建议收藏」

    ffmpeg安装及使用教程「建议收藏」ffmpeg安装及使用教程

    2025年8月29日
    5
  • ireport属性_显示非数值型数据怎么办

    ireport属性_显示非数值型数据怎么办1.结果显示为NULL: 处理方式: 1).把数据填充进list前进行处理 2).用条件表达式处理iReport的字段 $F{name}==null?”—”:$F{name}2.处理日期格式 处理方式: 1).把数据填充进list前进行处理 2).设置iReport字段为 new Java.text.SimpleDateFormat(“yyy

    2025年10月19日
    7
  • 关于c++操作符的优先级

    优先级从上到下依次递减,最上面具有最高的优先级,逗号操作符具有最低的优先级。所有的优先级中,只有三个优先级是从右至左结合的,它们是单目运算符、条件运算符、赋值运算符。其它的都是从左至右结合。具有最高优

    2021年12月20日
    59
  • mysql联合索引失效

    mysql联合索引失效联合索引,能够缩小查询范围的字段放在第一个,比如表sensor_coc_repay_feature存近一个月数据两千多万条,建立联合索引(time,distinct_id),按照查询select*fromsensor_coc_repay_featurewheredistinct_id=%sandtime>‘2022-02-20’,此时然后按照联合索引最左匹配有使用到了time,distinct_id,但是经过time查询后的数据还会是全表,mysql会认为该查询还不如走全表查询

    2025年9月3日
    12
  • oracle保留小数位数

    oracle保留小数位数公司需要处理一些报表,需要使用百分率,保留2位小数,只用round和trunc函数都可以实现(round(_data,2)),只是格式不是很工整,对格式要求不严谨的情况下使用round即可公司需要处理一些报表,需要使用百分率,保留2位小数,只用round和trunc函数都可以实现(round(_data,2)),只是格式不是很工整,对格式要求不严谨的情况下使用round即可.个人认为比较方便的一种selectdecode(n_jg,0,’0.00′,trim(to_char(n_jg,’999

    2022年7月24日
    7
  • jdbc连接mysql8.0数据库_java jdbc连接数据库步骤

    jdbc连接mysql8.0数据库_java jdbc连接数据库步骤首先确认自己的mySQL数据库是多少版本,5.0版本和8.0版本在代码上会有很大的不同并且驱动包也不同8.0使用的是com.mysql.cj.jdbc.Driver,5.0使用的是com.mysql.jdbc.Driver。下面直接上8.0的代码Class.forName(“com.mysql.cj.jdbc.Driver”);conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/地址?use

    2025年10月11日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号