Python data analysis (1)

Basic file operation I/O

The open function opens a file

Add +: means to open the current file in read-write mode (r+, w+, a+, rb+, rw+, ra+), the basic features are the same as those before the + sign is not applicable, and the operation results are slightly different. After adding the + sign, you can read and write as long as you open a file.           

Method 1: open() write() read()   

fo = open("foo.txt", "w")  #fo = open("文件","权限")   r+ "w"
print("文件名: ", fo.name)   #文件名
file.write("This is write content!")   	# 将字符串内容写入到文件中
fo.close()                        #关闭文件
fo = open("foo.txt", "r+")
str = fo.read(10)
print("读取的字符串是 : ", str)
# 关闭打开的文件
fo.close()

file location

The tell() method tells you the current position within the file, in other words, the next read or write will happen this many bytes after the beginning of the file.

# 查找当前位置
position = fo.tell()
print "当前文件位置 : ", position
 
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0)
str = fo.read(10)
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()

Rename and delete files

# Rename the file test1.txt to test2.txt.
os.rename( "test1.txt", "test2.txt" )
# Delete an existing file test2.txt
os.remove("test2.txt")

Directories in Python:

All files are contained in different directories, but Python can handle it easily. The os module has a number of methods that help you create, delete and change directories.

import os

#创建目录   os.mkdir("newdir")  之前没创建过

#os.mkdir("newdir2")

#查看当前工作目录  os.getcwd()  
print(os.getcwd())


#进入目录   os.chdir("/home/newdir1")  /

os.chdir("D:/PythonDemo/newdir1")
print(os.getcwd())

f1 = open("f11.txt","w+")
f1.write("哈哈哈哈哈哈哈哈哈")
f1.close()

# 删除”/tmp/test”目录  #only删除空目录
#os.rmdir( "/tmp/test"  )

 

Guess you like

Origin blog.csdn.net/JLwwfs/article/details/127299055