This time too, I will talk about reading and writing text in Python, which I often use.
sample.py
#-*- coding:utf-8 -*-
if __name__ == '__main__':
print "\ntest.Create txt and start a new line 1~Let me enter up to 100."
fw = open("test.txt","w")
for line in range(0,100):
number = line + 1
if line == 0: fw.write("%s"%number)
else: fw.write("\n%s"%number)
fw.close()
print "Input is complete.\n"
print "Then test2.Create txt and open the feeling with tabs 1~Let me enter up to 100."
fw2 = open("test2.txt","w")
for line2 in range(0,100):
number = line2 + 1
if line2 == 0: fw2.write("%s"%number)
else: fw2.write("\t%s"%number)
fw2.close()
print "Input is complete.\n"
print "test.The number of lines entered in txt will be displayed from now on."
fr = open("test.txt","r")
for line in fr:
len_item = sum(1 for line in fr)
print "In the text%There are s lines.\n"%(len_item+1)
fr.close()
print "test2.I will display what I entered in txt."
fr2 = open("test.txt","r")
for line2 in fr2:
print line2,
print ''
fr2.close()
print "The display is finished.\n"
print "That's all for this program. Thank you for your hard work.\n"
I put a little small material in various ways.
For example, the number of lines entered in " test.txt will be displayed from now on. The way to write
sum (1 for line in fr) written in "
.
This will tell you how many lines there are in the file.
Moreover, it seems that writing with sum (1 for line in fr)
will calculate faster than finding it by turning it in the outside for line in fr
.
In addition, I will display what I entered in `" test2.txt. "
print ''```
That part. By writing this, you can print the elements one by one.
# 3. Introduction of the site that was taken care of
A very helpful site: "[Read a file with Python](http://osksn2.hep.sci.osaka-u.ac.jp/~taku/osx/python/readfile.html)"
There are many samples and it is very useful m (_ _) m
Recommended Posts