2

So i wrote a little program in python which allows me to take a .csv file, filter out the lines i need and then export these into a new .txt file. This worked quite well, so i decided to make it more user friendly by allowing the user to select the file that should be converted by himself through the console (command line).

My problem: The file is imported as a .csv file but not exported as a .txt file which leads to my program overwriting the original file which will be emptied because of a step in my program which allows me to delete the first two lines of the output text.

Does anyone know a solution for this?

Thanks :)

import csv
import sys

userinput = raw_input('List:')
saveFile = open(userinput, 'w')

with open(userinput, 'r') as file:
    reader = csv.reader(file)
    count = 0

    for row in reader:
        print(row[2])
        saveFile.write(row[2] + ' ""\n')
saveFile.close()

saveFile = open(userinput, 'r')
data_list = saveFile.readlines()
saveFile.close()

del data_list[1:2]

saveFile = open(userinput, 'w')
saveFile.writelines(data_list)
saveFile.close()
Jakob Lsr
  • 23
  • 3

3 Answers3

1

I think you probably just want to save the file with a new name, this Extracting extension from filename in Python talks about splitting out the extension so then you can just add your own extension

you would end up with something like

name, ext = os.path.splitext(userinput)
saveFile = open(name + '.txt', 'w')
tam
  • 1,583
  • 2
  • 13
  • 25
1

Try This:

userinput = raw_input('List:')
f_extns = userinput.split(".")
saveFile = open(f_extns[0]+'.txt', 'w')
losforword
  • 90
  • 7
0

You probably just need to change the extension of the output file. Here is a solution that sets the output file extension to .txt; if the input file is also .txt then there will be a problem, but for all other extensions of the input file this should work.

import csv
import os

file_name = input('Name of file:')

# https://docs.python.org/3/library/os.path.html#os.path.splitext
# https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python
file_name, file_ext_r = os.path.splitext(file_name)
file_ext_w = '.txt'
file_name_r = ''.format(file_name, file_ext_r)
file_name_w = ''.format(file_name, file_ext_w)
print('File to read:', file_name_r)
print('File to write:', file_name_w)

with open(file_name_r, 'r') as fr, open(file_name_w, 'w') as fw:
    reader = csv.reader(fr)

    for i, row in enumerate(reader):
        print(row[2])

        if i >= 2:
            fw.write(row[2] + ' ""\n')

I also simplified your logic to avoid writting the first 2 lines to the output file; no need to read and write the output file again.

Does this work for you?

Ralf
  • 16,086
  • 4
  • 44
  • 68