[读取文件数据],open()的返回类型和【list.append(),造成显性写入\n】。方法参数的缺省带来的影响?

来源:互联网 发布:八爪鱼采集器的源码 编辑:程序博客网 时间:2024/05/29 16:16


#os.chdir('D:\IDE\workspace\testfiles')

os.chdir('D:/IDE/workspace/testfiles') #斜杠方向

print(os.getcwd())

输出为 D:\IDE\workspace\testfiles #斜杠方向不同


#打印文件'''    newline controls how universal newlines works (it only applies to text    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as    follows:        * On input, if newline is None, universal newlines mode is    enabled. Lines in the input can end in '\n', '\r', or '\r\n', and    these are translated into '\n' before being returned to the    caller. If it is '', universal newline mode is enabled, but line    endings are returned to the caller untranslated. If it has any of    the other legal values, input lines are only terminated by the given    string, and the line ending is returned to the caller untranslated.        * On output, if newline is None, any '\n' characters written are    translated to the system default line separator, os.linesep. If    newline is '' or '\n', no translation takes place. If newline is any    of the other legal values, any '\n' characters written are translated    to the given string.    '''data = open('sketch.txt') #返回类型:<class '_io.TextIOWrapper'>  data.seek(0)for each_item in data:    #each_item的类型为<class 'str'>    #以文件换行作为str的划分            print(each_item, end='')print(type(data))data.close()


print(os.getcwd())man = "各种字符串asdfghjkl。\n123456"myfile = open('myfile.txt','w')print(man, file=myfile)#将字符串写入文件myfile.close()#【注意】如果不关闭文件,下面命令无法执行。printfile(open('myfile.txt'))'''    打印结果为:    各种字符串asdfghjkl。    123456    【执行了换行操作】'''

def mycopy():    datain = []    data = open('file2.py')    for each in data:        datain.append(each)#【每次添加新元素时,把\n显性的写入】    newfile = open('file3.txt', 'w')    print(datain, file=newfile)#会把换行打印成\n    print_file(data)#【读源文件正确显示多行,副本文件为单行】    newfile.close()    print_file(open('file3.txt'))


#解决办法:qfile = open('wq.txt','w').writelines([l for l in open('ww.txt','r').readlines() if l[:-1].strip()

l[:-1]除去了字符串后面的\n,然后依次写入。在每次写入操作后会自动换行

参见:http://zhidao.baidu.com/question/554688895.html?fr=qrl&index=1&qbl=topic_question_1&word=python%20string%20%C9%BE%B3%FD

总结,错误的做法:

1.使用list.append(),造成显性写入\n

2.直接每行写入时,print操作会再次执行换行,造成每次多一个空行。


packle.dump(A, B) #把A的内容放入文件B,以Python的方式压缩数据

import picklemdata = [('a',1),('c','d')]print(mdata)with open('Picklefile.pickle','wb') as mysavedata:    pickle.dump(mdata, mysavedata)#将mdata压缩写入文件with open('Picklefile.pickle','rb') as myrestoredata:#读    mdata = pickle.load(myrestoredata)#理解为解压缩#list2 = open('file2.txt')print('解压缩后:')print(mdata)



def function(A, B, C) #不支持缺省参数还不知道为什么。不知道是headfirst python代码问题,还是我本地的问题

#会出现提示:<_io.TextIOWrapper name='file4.txt' mode='w' encoding='cp936'>

0 0