file
file打开方式
text = ''
file = open('poem.txt','w')
for line in file:
text = text + line
file.close() #注意记得close
print(result)
result = set(result) #把结果转化为set,去掉重复
file 读写
input_file = open('input.txt','r')
output_file = open('output.txt','w')
for line_str in input_file:
new_str = ''
line_str = line_str.strip()
for char in line_str:
new_str = char + new_str
print(new_str,file = output_file) # print to output file
print('line{:12s} reversed is {:s}'.format(line_str,new_str))
input_file.close()
output_file.close()
常用函数区别
reading
readline: 读一行,返回一个string
readlines: 读一个文件中的所有行,返回一个list(每行是一个element)
注意:这个方法不推荐,因为读很大的文件时候会生成一个很大的list,储存文件会很慢且低效。
read(size in bytes): 括号里可以是一个integer表示1个byte,默认是整个文件。
writing
write: 把一个string写成一个file,返回number of bytes(characters) written to the file。
注意: 只能是string,别的格式需要转成string
wordlist = ['First', 'Second', 'Third', 'Fourth']
outfile = open('outFile.txt', 'w')
for word in word list:
out file.write(word + ' line\n')
outfile.close()
注意在每行最后append \n 来得到多行文件
writelines: a sequence(e.g. a list of lines) 写成一个file
outfile = open('out.txt', 'w')
linelist = ['First line\n', 'Second line\n', 'Third line\n', 'Fourth line \n']
outfile.writelines(linelist)
outfile.close()
定位
file.seek(0) # go to the beginning of the file
file.tell() # report the position of the current file position relative to the beginning of the file in bytes
With statement
The process of opening and closing a file is a common enough event that Python provides a shortcut, the with statement. This statement makes it a little easier to open and file and ensures that a file, once opened, gets closed automatically without requiring the programmer to provide the actual close statement.
with expression as variable:
with open('temp.txt') as temp_file:
temp_file.readlines()
CSV
- 使用reader的前提是已经打开一个file而且生成了一个file object。
- csv.reader 和 file的区别是 csv.reader returns a single row of the file for each iteration (not necessary a line).
The returned value is a list of strings, where each element of list represents one of the fields of the row.
OS
os.getcwd()
os.chdir()
os.listdir()
os.path.isfile() # check if a file exists
os.path.isdir()
os.path.exists()
os.path.basename()
os.path.dirname()
os.path.split() # 返回 directory和file
os.path.splitext()
os.path.join()
path_str = os.getcwd()
os.walk(path_str)
网友评论