您的位置:首页 > 编程语言 > Python开发

2017/6/9-Python文件读写的方法

2017-08-31 10:03 806 查看
# 使用斜杠“/”: "c:/test.txt"… 不用反斜杠就没法产生歧义了
# 将反斜杠符号转义: "c:\\test.txt"… 因为反斜杠是转义符,所以两个"\\"就表示一个反斜杠符号
# file=open('D:\\jupyter\\test.txt')#
#file=open('D:/jupyter/test.txt')
#file=open('test.txt')#和程序在一个同一路径下
file=open('test.txt')
file.read()

'hi quincyqiang\nhow are you'

#模式描述
# http://www.yiibai.com/python3/python_files_io.html 
# 读文件有3种方法:read()将文本文件所有行读到一个字符串中。
#               readline()是一行一行的读
#               readlines()是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。
# 优点:readline()可以在读行过程中跳过特定行。 \

#第一种方法
file_1=open('test.txt')
file_2=open('output.txt','w')
while True:
line=file_1.readline()
print(line.strip())#取出换行
file_2.write(line)
if not line:
break
file_2.close()

hi quincyqiang
how are you

#第二种方法,使用for循环
file_2=open('output.txt','w')
for line in open('test.txt'):
print(line.strip())
file_2.write(line)
file_2.close()

hi quincyqiang
how are you

#第三种方法文件上下文
文件上下文管理器
with open('somefile.txt', 'r') as f:
data = f.read()

# Iterate over the lines of the file
with open('somefile.txt', 'r') as f:
for line in f:
# process line

# Write chunks of text data
with open('somefile.txt', 'w') as f:
f.write(text1)
f.write(text2)
...

# Redirected print statement
with open('somefile.txt', 'w') as f:
print(line1, file=f)
print(line2, file=f)


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: