如何在Python中读取和分割文件的每一行?
感谢StackOverflow,我现在可以读取和复制文件了。不过,我需要逐行读取一张图片文件,而且缓冲区数组不能超过3000个整数。我该怎么分隔这些行,读取它们,然后再复制呢?这样做是最好的方法吗?
这是我写的代码,感谢@Chayim的帮助:
import os
import sys
import shutil
import readline
source = raw_input("Enter source file path: ")
dest = raw_input("Enter destination path: ")
file1 = open(source,'r')
if not os.path.isfile(source):
print "Source file %s does not exist." % source
sys.exit(3)
file_line = infile.readline()
try:
shutil.copy(source, dest)
infile = open(source,'r')
outfile = open(dest,'r')
file_contents = infile.read()
file_contents2 = outfile.read()
print(file_contents)
print(file_contents2)
infile.close()
outfile.close()
except IOError, e:
print "Could not copy file %s to destination %s" % (source, dest)
print e
sys.exit(3)
我添加了 file_line = infile.readline() 但我担心infile.readline()会返回一个字符串,而不是整数。此外,我该如何限制它处理的整数数量呢?
1 个回答
2
我觉得你想做的事情大概是这样的:
infile = open(source,'r')
file_contents_lines = infile.readlines()
for line in file_contents_lines:
print line
这段代码会把文件里的所有行都读取出来,并把每一行放到一个列表里,列表中的每个元素就是文件的一行。
你可以看看这里的文档,了解更多信息。