简体   繁体   中英

How to create a text file in python without csv.writer?

I need a comma seperated txt file with txt extension. "a,b,c"

I used csv.writer to create a csv file changed the extension. Another prog would not use/process the data. I tried "wb", "w."

F = open(Fn, 'w')
w = csv.writer(F)
w.writerow(sym)
F.close()

opened with notepad ---These are the complete files. Their file: created using their gui used three symbols

PDCO,ICUI,DVA

my file : created using python

PDCO,ICUI,DVA

Tested: open thier file- worked, opened my file - failed. Simple open and close with save in notepad. open my file-- worked

Works= 'PDCO,ICUI,DVA' 
Fails= 'PDCO,ICUI,DVA\r\r\n' 

Edit: writing txt file without Cvs writer.....

sym = ['MHS','MRK','AIG']

with open(r'C:\filename.txt', 'w') as F:    # also try 'w'
    for s in sym[:-1]:                      # separate all but the last
        F.write(s + ',')                    # symbols with commas
        F.write(sym[-1])                    # end with the last symbol

To me, it look like you don't exactly know you third party application input format. If a .CSV isn't reconized, it might be something else.

Did you try to change the delimiter fromn ';' to ','

import csv
spamWriter = csv.writer(open('eggs.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

Take a look in the CSV Python API

I think the problem is your file write mode, as per CSV file written with Python has blank lines between each row

If you create your csv file like

csv.writer(open('myfile.csv', 'w'))

csv.writer ends its lines in '\\r\\n', and Python's text file handling (on Windows machines) then converts '\\n' to '\\r\\n', resulting in lines ending in '\\r\\r\\n'. Many programs will choke on this; Notepad recognizes it as a problem and strips the extra '\\r' out.

If you use

csv.writer(open('myfile.csv', 'wb'))

it produces the expected '\\r\\n' line ending, which should work as desired.

Edit: @senderle has a good point; try the following:

goodf = open('file_that_works.txt', 'rb')
print repr(goodf.read(100))
badf =  open('file_that_fails.txt', 'rb')
print repr(badf.read(100))

paste the results of that here, so we can see how the two compare byte-for-byte.

  1. So, I save as text file.

  2. Now, create my own txt file with python.

What are the exact differences between their file and your file? Exact.

I suspect that @Hugh's comment is correct that it's an encoding issue.

When you do a Save As in notepad, what's selected in the Encoding dropdown? If you select different encodings do some or all of those fail to be opened by the 3rd party program?

Try this:

with open('file_that_works.csv', 'rb') as testfile:     # file is automatically
    d = csv.Sniffer().sniff(testfile.read(1024))        # closed at end of with
                                                        # block
with open(Fn, 'wb') as F:       # also try 'w'
    w = csv.writer(F, dialect=d)
    w.writerow(sym)

To explain further: this looks at a sample of a working .csv file and deduces its format. Then it uses that format to write a new .csv file that, hopefully, will not have to be resaved in notepad.


Edit: if the program you're using doesn't accept multi-line input (?!) then don't use csv. Just do something like this:

syms = ['JAGHS','GJKDGJ','GJDFAJ']
with open('filename.txt', 'wb') as F:       
    for s in syms[:-1]:                     # separate all but the last
        F.write(s + ',')                    # symbols with commas
    F.write(syms[-1])                       # end with the last symbol

Or more tersely:

with open('filename.txt', 'wb') as F:
    F.write(','.join(syms))

Also, check different file extensions (ie .txt, .csv, etc) to make sure that's not the problem. If this program chokes on a newline, then anything is possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM