0

Hey guys,

I want to write a program which scans the first line in a data file and sees whether it is delimited by "\t", "," or " ". If it is any of these, I want to keep the line, else, I want to raise some sort of error like "IMPROPER FORMATTING".

I have attempted it with this:

f = open(file, 'r')

	first_line = f.readline()
	first_line = first_line.strip()

	try:
	
		sline = first_line.split(" ")
		if len(sline > 1):
			pass
	
	except:TypeError





	try:

		sline = first_line.split('\t')
		if len(sline > 1):
			pass


	try:
	
		sline = first_line.split(',')
		if len(sline > 1):
			pass
	
	except:TypeError



	print sline

Strangely enough, it works, but only for files whose delimiter are the last one that I have. For example, if I have a file delimited by ',' then because my last delimiter try statement was for a comma, the file outputs what I eventually want it to. But if I have a tab delimited file, I have to put the "try split('t')" statement last. Perhaps I am wrong in using this try feature.

Any suggestions?

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by woooee
0

delimited by "\t", "," or " ". If it is any of these, I want to keep the line

Just test for any one in a line.

if ("\t" in line) \
or ("," in line) \
or " " in line:
    print "keep this line", line
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.