Reputation: 139
I've a data
0002 100789 Clearing charges 1000.00- Pending
0002 239890 Cheque bounce 20.00 client accepted
0001 789652 Export docs 200.00 Bank of Italy charges
Output file should be
0002 100789 Clearing charges 1000.00- Pending
0002 239890 Cheque bounce 20.00 client accepted
0001 789652 Export docs 200.00 Bank of Italy charges
my code
import pandas as pd
df=pd.read_fwf("C:\\csv_in\\back_trans.csv",widths=[4,9,16,15,23],header=None)
result=df.to_string(index=False,header=None)
new_file=open("C:\\csv_out\\back_trans.csv",mode="a+",encoding="utf-8")
new_file.writelines(result)
for line in new_file:
print(line)
new_file.close()
Creating blank rows, which function I've to use. Please throw some lights on this.
Upvotes: 1
Views: 95
Reputation: 5686
You can use df.to_csv()
to make your life a litter easier (and your code a little faster).
df.to_csv()
then has an argument line_terminator
. This controls what separates one row from another in the resulting .csv
file.
How exactly a newline is encoded depends on your operating system. We can use os.linesep
to find out the newline character for your OS (I can see here that you're running windows, but using os.linesep
would be considered good practice anyway, and colleagues running a different OS will thank you).
Here's an MWE:
import os
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 10, size=(10, 3)))
df.to_csv("C:\\csv_out\\back_trans.csv", line_terminator=os.linesep*2)
This gave me the file contents as
❯ cat C:\\csv_out\\back_trans.csv
,0,1,2
0,4,3,4
1,1,1,8
2,4,7,1
3,3,3,7
4,8,5,0
5,7,5,3
6,1,1,0
7,0,3,4
8,1,7,1
9,1,2,9
Upvotes: 1