haibaraxx的个人博客分享 http://blog.sciencenet.cn/u/haibaraxx

博文

Python 2: read and write from a file

已有 2081 次阅读 2016-3-8 04:01 |个人分类:Python|系统分类:科研笔记|关键词:学者| and, from, write, read, file

# send information to the "Command Output"
print "hello world"

# creat a new file and write it

f = open('helloworld.txt','w')     # creat a txt file in the working directory. w stands for "write". when using w, the program will overwite whatever might have been contained in the file.
f.write('hello world!!')    # write "hello world" to the txt file.
f.close()    # close the file.

f = open('/Users/Yangyang/Documents/acs_230715.dat','w')    # creat a dat file in the given path.
f.write('hello world!!')
f.close()

# read a file

f = open('helloworld.txt','r')    # open the txt file and read from it.
m = f.read()    # copy the contents of the above txt file into m.
print m    # send the information contained in m to the "Command Output"
f.close()

f = open ('/Users/Yangyang/Documents/acs_2_230715.dat','r')    # open the dat file from a special path and read from it.
n = f.read()    # copy the contents of the above dat file into n.
print n
f.close()

# append to a pre-existing file

f = open('helloworld.txt','a')
f.write('n'+'hello world')    # 'n' stands for new line. add 'hello world' in the new line of the txt file.
f.close()



https://m.sciencenet.cn/blog-3031432-961140.html

上一篇:LibreOffice: freezing rows and columns in LibreOffice Calc
下一篇:Python 2: open a webpage

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-6-14 00:28

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部