[英]Automate conversion txt to xls
I am looking for the cheapest way of automating the conversion of all the text files (tab-delimited) in a folder structure into .xls format, keeping the shape of columns and rows as it is. 我正在寻找最便宜的方法来自动将文件夹结构中的所有文本文件(制表符分隔)转换为.xls格式,保持列和行的形状不变。
Edit: this did the trick: 编辑:这就是诀窍:
import xlwt
import xlrd
f = open('Text.txt', 'r+')
row_list = []
for row in f:
row_list.append(row.split())
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
for item in range(len(column)):
worksheet.write(item, i, column[item])
workbook.save('Excel.xls')
i+=1
The easiest way would be to just rename all of the files from *.txt to *.xls. 最简单的方法是将所有文件从* .txt重命名为* .xls。 Excel will automatically partition the data, keeping the original shape. Excel将自动对数据进行分区,保持原始形状。
I'm not going to write your code for you, but here is a head start: 我不会为你编写代码,但这是一个良好的开端:
os.listdir()
您可以使用os.listdir()
列出目录内容 os.path.isdir()
and os.path.isfile()
to see if each 'thing' you just found in your intial directory is a file or a directory, and act on accordingly 您可以使用os.path.isdir()
和os.path.isfile()
来查看您在初始目录中找到的每个“东西”是文件还是目录,并相应地执行操作 os.rename()
to rename a file and os.remove()
to delete a file 您可以使用os.rename()
重命名文件,使用os.remove()
删除文件 os.path.splitext()
to split the files name and extension, or just file.endswith('.txt')
to work on only the correct files 您可以使用os.path.splitext()
来分割文件名和扩展名,或者只使用file.endswith('.txt')
来处理正确的文件 How about this? 这个怎么样?
import xlwt
textfile = "C:/Users/your_path_here/Desktop/test.txt"
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'
#for textfile in textfiles:
f = open(textfile, 'r+')
row_list = []
for row in f:
row_list.append(row.split('|'))
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
for item in range(len(column)):
value = column[item].strip()
if is_number(value):
worksheet.write(item, i, float(value), style=style)
else:
worksheet.write(item, i, value)
i+=1
workbook.save(textfile.replace('.txt', '.xls'))
Sorry, must have pasted in the wrong thing... 对不起,一定是贴错了...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.