简体   繁体   中英

How to read and divide individual lines of a file in python?

Thanks to stackoverflow, I am able to read and copy a file. However, I need to read a picture file one line at a time, and the buffer array can't exceed 3,000 integers. How would I separate the lines, read them, and then copy them? Is that the best way to execute this?

Here is my code, courtesy of @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)

I added file_line = infile.readline() but I'm concerned that infile.readline() will return a string, instead of integers. Also, how do I limit the number of integers it processes?

I think you want to do something like this:

infile = open(source,'r')

file_contents_lines = infile.readlines()

for line in file_contents_lines:
    print line

This will get you all the lines in the file and put them into a list containing each line as an element in the list.

Take a look at the documentation here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM