如何多次循环此python代码

时间:2014-05-02 02:22:30

标签: python loops csv for-loop jpeg

我有一个csv文件,其中包含大约380个名字,如下所示:

  1. John Smith
  2. Alert Johnson
  3. Corey Johnson
  4. 等等

    我能够导入第一行并将其打印到图像上。 但是,我想要做的是能够循环它并读取csv文件中的所有名称,然后在图像上打印每个名称。 有380个名字,应该有380个带有名字的图像。

    基本上我想循环它,直到它读取CSV文件中的所有名称并为每个名称保存图像文件。

    有人可以帮助我如何让它循环读取csv上的所有名字吗?

        import PIL
        from PIL import ImageFont
        from PIL import Image
        from PIL import ImageDraw
        import ImageFont, ImageDraw
        import csv
        import sys
    
    
    
        #opens csv file and reads the first line. Using rstrip to get rid of special character at end
        with open('Names.csv', 'rU') as f:
                for name in f:
            names = f.readline().rstrip()
                names2 = f.readline().rstrip()
    
    
        #font and size on local machine
        font = ImageFont.truetype("/Library/Fonts/Microsoft/Arial.ttf", 150)
    
    
        #This is the text it will print.
        text = names
    
    
        #color of text = black
        tcolor = (255,0,0)
    
    
        #opens image in the same folder
        img = Image.open("Certificate.jpg") #opens image in the same folder
    
    
        #gets the height and width of the jpg
        width, height = Image.open(open("Certificate.jpg")).size
    
    
        #defining "draw" to draw onto image
        draw = ImageDraw.Draw(img)
    
    
        #define variables x = width and y = height
        text_x, text_y = font.getsize(text)
    
    
        #find the middle of width using this equation and store into "x"
        x = (width - text_x)/2
    
    
        #find the middle of height using this equation and store into "y"
        y = (height - text_y)/2
    
    
        #calls "draw" and writes "text" using middle of jpg
        draw.text ( (x,y), text, font=font, fill=tcolor)
    
    
        #saves image
        img.save("test.jpg")
    

    我得到的错误: 文件“full2.py”,第14行,in      names = f.readline()。rstrip() valueError:混合迭代和读取方法会丢失数据

    我可以使用While代替For。但是,我不知道如何实现While循环以保持读取行并打印/保存图像。

1 个答案:

答案 0 :(得分:2)

你应该使用for循环遍历每一行,例如for name in f:

    import PIL
    from PIL import ImageFont
    from PIL import Image
    from PIL import ImageDraw
    import ImageFont, ImageDraw
    import csv
    import sys



    #opens csv file and reads the first line. Using rstrip to get rid of special character   at end
    with open('Names.csv', 'rU') as f:
        for name in f: 
           #need to put all the statements below in this code block.