Python基础 8 文件的读写操作

作者: gavin 分类: Python,Python基础 发布时间: 2020-10-20 09:59
file1 = open('name.txt','r',encoding='utf-8')
file2=file1.read()
print(file2)
file1.close()

#open的参数w写入、a追加、r读取
file1 = open('name.txt', 'w',encoding='utf-8')
file1.write('张无忌\n')
file1.write('宋青书\n')
file1.close()


# 普通写法
file1 = open('abc.txt','a') 
file1.write('张无忌') 
file1.close()

# 使用with关键字的写法
with open('abc.txt','a') as file1:
#with open('文件地址','读写模式') as 变量名:
    #格式:冒号不能丢
    file1.write('张无忌') 
    #格式:对文件的操作要缩进
    #格式:无需用close()关闭

readlines&writelines的使用和数据处理

file1 = open('name.txt','r',encoding='utf-8')
file2=file1.read()
print(file2)
file1.close()

file1 = open('name.txt', 'w',encoding='utf-8')
file1.write('张无忌\n')
file1.write('宋青书\n')
file1.close()


# 普通写法
file1 = open('abc.txt','a') 
file1.write('张无忌') 
file1.close()

# 使用with关键字的写法
with open('abc.txt','a') as file1:
#with open('文件地址','读写模式') as 变量名:
    #格式:冒号不能丢
    file1.write('张无忌') 
    #格式:对文件的操作要缩进
    #格式:无需用close()关闭
file = open('/Users/Ted/Desktop/scores.txt','r',encoding='utf-8') 
file_lines = file.readlines()
file.close()

final_scores = [] 

for i in file_lines:
    data =i.split()    
    sum = 0                    
    for score in data[1:]:     
        sum = sum + int(score)     
    result = data[0]+str(sum)+'\n'    
    final_scores.append(result)

winner = open('/Users/Ted/Desktop/winner.txt','w',encoding='utf-8') 
winner.writelines(final_scores)
winner.close()

读取CSV转换为列表的方式

import csv

with open("test.csv",newline = '')  as f:
    reader = csv.reader(f)
    #使用csv的reader()方法,创建一个reader对象
    for row in reader: 
    #遍历reader对象的每一行
        print(row)

print("读取完毕!")

发表回复

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