Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何将输出文件打印成两列?_Python_Excel - Fatal编程技术网

Python如何将输出文件打印成两列?

Python如何将输出文件打印成两列?,python,excel,Python,Excel,我不知道为什么我的格式看起来这么糟糕,所以我提供了一个截图,谢谢 这是我的密码: import xlrd #read excel import urllib.request #read url path= 'F:/4480/ASSIGNMENT.xlsx' #my excel path data = xlrd.open_workbook(path) #myexcel table=da

我不知道为什么我的格式看起来这么糟糕,所以我提供了一个截图,谢谢

这是我的密码:

import xlrd                       #read excel
import urllib.request             #read url


path= 'F:/4480/ASSIGNMENT.xlsx'           #my excel path
data = xlrd.open_workbook(path)          #myexcel

table=data.sheets()[0]              #first sheet


for x in table.col_values(0):       #first column(URL column)
    print (x)
    try :
        response = urllib.request.urlopen(x)
        print(response.getheader('ETag'))
    except :
        print("not url")
因此,基本上,输出是:

image URL
not url
http://images.ctfassets.net/55tpbg0qcsp4/1xjp4PdyFy2eUCIOkSOMWw/a923617148e873a8304477043386602d/1000x700.jpg?w=284&h=240
"42b140ed9e700be672c586933f45f792"
http://images.ctfassets.net/55tpbg0qcsp4/5zeVQCnhqowcwiIw4kM80S/f70edd51832e8640f72c375cb1d72b6b/nagative_farewell4.jpg?w=284&h=240
"4ea3a7262ceb6d451cfe6472eea82983"
但我想要的是:

image URL    NOT URL
HTTP://      "XXXX"

然后将输出保存到另一个文件中(而且,我想使用列值,那么我应该使用哪个文件?txt?

您可以使用CSV文件作为输出,并将分隔符设置为选项卡

import csv
import xlrd                    
import urllib.request             

csv_file = open('output.csv', 'wb')
writer = csv.writer(csv_file , delimiter='\t')

path= 'F:/4480/ASSIGNMENT.xlsx'
data = xlrd.open_workbook(path)

table = data.sheets()[0]

writer.writerow(('image URL', 'not url')) 

for x in table.col_values(0):
    try:
        response = urllib.request.urlopen(x)
        # Write normal row
        writer.writerow((x, response.getheader('ETag')))
    except:
        # Write invalid row
        writer.writerow((x, "not url"))

# Finally close the file
csv_file.close()
当然,如果您想要一个普通的CSV文件,您可以调整它并使用逗号(
delimiter=','
)作为分隔符


编辑:将示例代码更改为使用excel读取功能

您可以尝试将其保存为csv文件,但使用制表符而不是通常的逗号作为分隔符。您好,先生,您能告诉我怎么做吗?我是pythonI的新手,我已经添加了一个关于如何通过修改原始代码来编写CSV文件的答案。