1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python文件和数据的格式化_Python在文本文件中格式化特定数据

python文件和数据的格式化_Python在文本文件中格式化特定数据

时间:2020-04-16 13:35:20

相关推荐

python文件和数据的格式化_Python在文本文件中格式化特定数据

谢谢你们的帮助。作为一个新手,我最终得到的代码不是那么优雅,但它仍然起作用:)。在#open the file and create the CSV after filtering the input file.

def openFile(filename, keyword): #defines the function to open the file. User to pass two variables.

list = []

string = ''

f = open(filename, 'r') #opens the file as a read and places it into the variable 'f'.

for line in f: #for each line in 'f'.

if keyword in line: #check to see if the keyword is in the line.

list.append(line) #add the line to the list.

print(list) #test.

for each in list: #filter and clean the info, format the info into a CSV format.

choppy = each.partition(': ') #split to remove the prefix.

chunk = choppy[2] #take the good string.

choppy = chunk.partition(' :') #split to remove the suffix.

chunk = choppy[0] #take the good string.

strsplit = chunk.split(' ') #split the string by spaces ' '.

line = strsplit[0] + ',' + strsplit[1] + ',' + strsplit[2] + ',' + strsplit[3] + ' ' + strsplit[4] + ' ' + strsplit[5] + '\n' #concatenate the strings.

string = string + line #concatenate each line to create a single string.

print(string) #test.

f = open(keyword + '.csv', 'w') #open a file to write.

f.write(string) #write the string to the file.

f.close() #close the file.

openFile('russtest.txt', 'cat')

openFile('CRON ENROL LOG 13.txt', 'field 4')

谢谢:)。在

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。