python怎么读(python怎么读取csv文件)

时间:2023-08-12 浏览:80 分类:问题百科

打开或是创建文件

#!/bin/bash/env python

#coding:utf8

context = '''hello world

hello python'''

f = file('hello.txt','w') #打开文件。若文件不存在python怎么读,则创建文件,打开方式为'w'

f.write(context) #把字符串写入文件

f.colse() #关闭文件

读取文件

#!/bin/bash/env python

#coding:utf8

方法一:使用readline()读文件f = open('hello.txt')

while True:

line = f.readline()

if line:

print line

else

break

方法二:使用readlines()读文件f = file('hello.txt')

lines = f.readlines()

for line in lines

print line

f.close()

方法三:使用read()读文件f = open("hello.txt")

context = f.read()

print context

f.close()

  补充:

  f.read(5):表示读取5个字符;

  f.tell():表示当前文件读取的位置

文件的写入

#!/bin/bash/env python

#coding:utf8

方法一:使用writelines()写文件f = file('hello.txt','w+') #w+:表示创建并写入

li = ['hello world ','hello python ']

f.writelines(li)

f.close()

方法二:使用write(),a+追加新的内容f = file('hello.txt','a+') #a+:表示追加

new_text = "goodbye"

f.write(new_text)

f.close()

文件的删除

#!/bin/bash/env python

#coding:utf8

import os

f = file('hello.txt','w')

if os.path.exists("hello.txt"): #删除前,先判断文件是否存在

os.remove("hello.txt")

文件的复制

#!/bin/bash/env python

#coding:utf8

方法一:通过read()和write()实现src = file('hello.txt','r')

drc = file('hello2.txt','w')

drc.write(src.read())

src.close()

drc.close()

方法二:通过shutil模板实现文件的拷贝import shutil

shutil.copyfile("hello.txt","hello2.txt") # 将hello.txt复制到hello2.txt

shutil.move("hello.txt","../") #将hello.txt剪切到上一层目录

shutil.move("hello2.txt","hello3.txt") #将hello2.txt重命名为hello3.txt

文件的重命名

#!/bin/bash/env python

#coding:utf8

#修改文件名

import os

li = os.listdir(".") #获取当前目录下的文件列表

print li

if "hello.txt" in li:

os.rename("hello.txt","hi.txt")

elif "hi.txt" in li:

os.rename("hi.txt","hello.txt")

#修改文件的后缀名

import os

files = os.listdir(".")

for filename in files:

pos = filename.find(".")

if filename[pos+1:] == "html":

newname = filename[:pos+1] + "htm"

os.rename(filename,newname)

#修改后缀名2

import os

files = os.listdir(".")

for filename in files:

li = os.path.spiltext(filename)

if li[1] == "html"

newname = li[0] + "htm"

os.rename(filename,newname)

python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。

python学习交流群:308754087 里面也会不定时分享关于Python的免费学习资料,欢迎想学习的小伙伴的加入,python有你更精彩python怎么读!嘿嘿!!

os.getcwd()#得到当前工作目录,即当前Python脚本工作的目录路径

os.listdir()#返回指定目录下的所有文件和目录名

os.remove()#函数用来删除一个文件

os.removedirs(r“c:python”)#删除多个目录

os.path.isfile()#检验给出的路径是否是一个文件

os.path.isdir()#检验给出的路径是否是一个目录

os.path.isabs()#判断是否是绝对路径

os.path.islink ( filename )#检查是否快捷方式

os.path.exists()#检验给出的路径是否真地存

os.path.splitext()#分离扩展名

os.path.dirname()#获取路径名

os.path.basename()#获取文件名

os.system()#运行shell命令

os.getenv() 与os.putenv()#读取和设置环境变量

os.rename(old, new)#重命名

os.makedirs(r“c:python est”)#创建多级目录

os.mkdir(“test”)#创建单个目录

os.stat(file)#获取文件属性

os.chmod(file)#修改文件权限与时间戳

os.exit()#终止当前进程

os.path.getsize(filename)#获取文件大小

  内容不完善,剩下的就靠各位自我解决了,哈哈哈哈哈哈哈哈!!