700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > pythonfor循环文件写入失败_Python:使用for循环写入文件

pythonfor循环文件写入失败_Python:使用for循环写入文件

时间:2020-12-12 08:41:58

相关推荐

pythonfor循环文件写入失败_Python:使用for循环写入文件

这个程序应该按照您的要求来做,并且允许在读取文件时修改它。每一行被读取,转换成大写,然后写回源文件。由于它是逐行运行的,它需要的最大额外内存将与最长行的长度有关。在

例1def main():

with get_file('Enter filename: ') as file:

while True:

position = file.tell() # remember beginning of line

line = file.readline() # get the next available line

if not line: # check if at end of the file

break # program is finished at EOF

file.seek(position) # go back to the line's start

file.write(line.upper()) # write the line in uppercase

def get_file(prompt):

while True:

try: # run and catch any error

return open(input(prompt), 'r+t') # r+t = read, write, text

except EOFError: # see if user if finished

raise SystemExit() # exit the program if so

except OSError as error: # check for file problems

print(error) # report operation errors

if __name__ == '__main__':

main()

下面的内容与您在上面看到的类似,但是在二进制模式下工作,而不是文本模式。它不是在行上操作,而是基于给定的BUFFER_SIZE分块处理文件,并且可以更高效地操作。如果您希望程序检查它是否正常运行,主循环下的代码可能会替换循环中的代码。assert语句检查一些假设。在

例2

^{pr2}$

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。