Reputation: 33
I want to create a txt File so I used this.
df1.to_csv('C:/Users/junxonm/Desktop/Filetest.txt',sep=" " ,index=False, header=False)
I can completely remove the separator
I tried this...
df1.to_csv('C:/Users/junxonm/Desktop/Filetest.txt',sep="" ,index=False, header=False)
And this...
df1.to_csv('C:/Users/junxonm/Desktop/Filetest.txt',sep=str('') ,index=False, header=False)
both are not working
Traceback (most recent call last):
File "C:/Users/junxonm/PycharmProjects/kemper/JDSNFILE2.py", line 371, in <module>
df1.to_csv('C:/Users/junxonm/Desktop/Filetest.txt',sep=str(""),index=False, header=False)
File "C:\Program Files\Python37\lib\site-packages\pandas\core\generic.py", line 3228, in to_csv
formatter.save()
File "C:\Program Files\Python37\lib\site-packages\pandas\io\formats\csvs.py", line 200, in save
self.writer = UnicodeWriter(f, **writer_kwargs)
File "C:\Program Files\Python37\lib\site-packages\pandas\io\common.py", line 517, in UnicodeWriter
return csv.writer(f, dialect=dialect, **kwds)
TypeError: "delimiter" must be a 1-character string
Have you any tips or some other ideas??
Thanks a lot
Upvotes: 3
Views: 3790
Reputation: 1
Unfortunately sep='' or None etc will result in "TypeError: "delimiter" must be a 1-character string"... so to print just the dataframe values you'd need to concatenate them and write them out the old fashioned way:
# Concatenate all values in the DataFrame
concatenated_data = df_values.apply(lambda row: ''.join(map(str, row)), axis=1)
# Write the concatenated data to a file
with open(write_path, 'w') as file:
file.write('\n'.join(concatenated_data))
Upvotes: 0
Reputation: 148880
The problem is that CSV stands for Comma Separated Fields. Variants allow to replace the comma with another one character long separator. Then intend is to always be able to extract individual fields back from the csv file. If the separator is empty, it is impossible to extract back fields so it cannot be a CSV file. Full stop. That is the reason why to_csv
insist on having a one character long delimiter. If you want to print the fields with no separator and a system default end of file, you should use print
instead of to_csv
:
with open('C:/Users/junxonm/Desktop/Filetest.txt', 'w') as fd:
for i in range(len(df1)):
print(df1.iloc[i,:], sep='', file=fd)
Upvotes: 1
Reputation: 1336
You can try this example
### ...
df.to_csv('test.txt',
header=None,
sep=" ",
quoting=csv.QUOTE_NONE,
escapechar=" ")
Upvotes: 0
Reputation: 3961
Try to write your pandas dataframe to the new text file like this (use a raw-string for your filename, and use None values instead of False for header and index):
df1.to_csv(r'C:/Users/junxonm/Desktop/Filetest.txt',
header=None,
index=None,
sep=' ',
mode='w'
)
Upvotes: 1