简体   繁体   English

从文本转换为CSV后为空文件

[英]Empty file after converting from text to CSV

I have been writing a short piece of python code to download a data file from a website and write it to a text file (which it does successfully). 我一直在编写一小段python代码,以从网站下载数据文件并将其写入文本文件(成功完成)。 Now I want to take that text file and convert it to CSV format. 现在,我要获取该文本文件并将其转换为CSV格式。 I have been using the responses from questions like "How to convert from txt to csv" but still come to the same end, which is that the CSV file is created successfully and the code executes without error, only the CSV file is empty, short of the column titles I have defined. 我一直在使用诸如“如何从txt转换为csv”之类的问题的答案,但仍然走到了最后,即成功创建了CSV文件,并且代码没有错误地执行,只有CSV文件为空,简短我定义的列标题。

import csv
import requests
res = requests.get('https://www.physics.rutgers.edu/~saurabh/mlcs2k2/vectors_R.dat')
res.status_code = requests.codes.ok


textfile = open("textfile.txt","w")
textfile.write(res.text)


with open('textfile.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('csvfile.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('Phase', 'M^0_R', 'P_R', 'Q_R')) #Prints correctly                                                                                                            
        writer.writerows(lines)

When you write data to textfile, you leave the file open. 将数据写入文本文件时,将文件保持打开状态。 Therefore when you reopen it later, the cursor is already in the end of the file, and iterating over lines only continues forward from the cursor, not from the beginning of the file. 因此,当您稍后重新打开它时,光标已经在文件的末尾,并且遍历行仅从光标开始,而不是从文件的开头继续。

Fix this by closing file after opening: 通过打开后关闭文件来解决此问题:

textfile = open("textfile.txt","w")
textfile.write(res.text)
textfile.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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