I have a Python script that reads a .xls file and uses a loop to remove all of the unnecessary returns inside of each row. So far my script can go through a row that I specify and remove the returns, but I want it to automatically go through every row and remove all the unnecessary returns. Here is my script -
import xlrd
import xlwt
# function for removing returns in file
edits_returns = ''
def remove_returns1(row, column):
global edits_returns
cell_hold = sheet.cell(row, column).value
cell_hold_str = str(cell_hold)
if "\n" in cell_hold_str:
edits_returns = edits_returns + ('Return(s) replaced in (row %d : cell %d.)\n' % (row, column))
out_cell = cell_hold_str.replace('\n', '')
return out_cell
# obtaining filename
fname = raw_input('Input Filename > ')
# opening file
workbook = xlrd.open_workbook(fname)
sheet = workbook.sheet_by_index(0)
# informing user of # of rows and columns
print "\nNumber of rows: %d" % sheet.nrows
print "Number of Columns: %d\n" % sheet.ncols
# removing returns by row
column = 0
while column < sheet.ncols:
new_value = remove_returns1(34, column)
column += 1
print new_value,
# printing the edits
print "\n\n", edits_returns
My questions
- How can I iterate through every row automatically instead of manually?
- Is there a better way to print the edit results as seen in
edit_results? (I plan to make this script do more than just remove returns in the future) - Am I doing something redundant or can something I've written in my script be done differently?
Example input:
10/13/15 mcdonalds\n $20 0.01%
10/13/15 mcdonalds\n $20 0.01%
Example output:
10/13/15 mcdonalds $20 0.01%
10/13/15 mcdonalds $20 0.01%
- All of the rows are still on their own line. they are not attached.
Example output from one of the provided answers:
10/13/15 mcdonalds $20 0.01%10/13/15 mcdonalds $20 0.01%
This appears close, but is still not what I'm looking for.
Thanks in advance! I'm open to all constructive criticism.
\nwith''for each column?