python 写 txt,,python写txt


python写txt,之前写过jason的,和写txt有点区别,记录下。

import osdef touch(path):u = ‘12‘u1= ‘34‘with open(path, ‘w‘) as f:f.write(u)f.write(‘\t‘)f.write(u1)#os.utime(path, None)path = "creativeFile.txt"touch(path)

  1.打开的模式有几种(转自http://blog.csdn.net/adupt/article/details/4435615)

mode是打开的模式,可选的值为r w a U,分别代表读(默认) 写 添加支持各种换行符的模式。用w或a模式打开文件的话,如果文件不存在,那么就自动创建。此外,用w模式打开一个已经存在的文件时,原有文件的内容会被清空,因为一开始文件的操作的标记是在文件的开头的,这时候进行写操作,无疑会把原有的内容给抹掉。由于历史的原因,换行符在不同的系统中有不同模式,比如在 unix中是一个/n,而在windows中是‘/r/n’,用U模式打开文件,就是支持所有的换行模式,也就说‘/r’ ‘/n‘ ‘/r/n‘都可表示换行,会有一个tuple用来存贮这个文件中用到过的换行符。不过,虽说换行有多种模式,读到python中统一用/n代替。在模式字符的后面,还可以加上+ b t这两种标识,分别表示可以对文件同时进行读写操作和用二进制模式、文本模式(默认)打开文件。

2.注意python是没法写int型的,必须是string。http://stackoverflow.com/questions/11160939/writing-integer-values-to-a-file-using-out-write。

解释就是:

write()only takes asingle stringargument, so you could do this:

outf.write(str(num))

outf.write(‘{}‘.format(num))  # more "modern"outf.write(‘%d‘ % num)        # deprecated mostly

Also note thatwritewill not append a newline to your output so if you need it you‘ll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7outf.write(‘{:03d}\n‘.format(num))num = 12outf.write(‘%03d\n‘ % num)

to get three spaces, with leading zeros for your integer value followed by a newline:

007012

format()will be around for a long while, so it‘s worth learning/knowing.

python 写 txt

评论关闭