Home > Mobile >  My code is not working properly only on my device
My code is not working properly only on my device

Time:09-10

I created a program to create a csv where every number from 0 to 1000000

import csv

nums = list(range(0,1000000))
with open('codes.csv', 'w') as f:
    writer = csv.writer(f)
    for val in nums:
        writer.writerow([val])

then another program to remove a number from the file taken as input

import csv
import os

while True:
    members= input("Please enter a number to be deleted: ")
    lines = list()
    with open('codes.csv', 'r') as readFile:
        reader = csv.reader(readFile)
        for row in reader:
                if all(field != members for field in row):
                    lines.append(row)
                else:
                    print('Removed')

    os.remove('codes.csv')

    with open('codes.csv', 'w') as writeFile:
        writer = csv.writer(writeFile)
        writer.writerows(lines)

The above code is working fine on any other device except my pc, in the first program it creates the csv file with empty rows between every number, in the second program the number of empty rows multiplies and the file size also multiples. what is wrong with my device then?

Thanks in advance

CodePudding user response:

I think you shouldn't use a csv file for single column data. Use a json file instead.

And the code that you've written for checking which value to not remove, is unnecessary. Instead you could write a list of numbers to the file, and read it back to a variable while removing a number you desire to, using the list.remove() method.

And then write it back to the file.

Here's how I would've done it:

import json

with open("codes.json", "w") as f:  # Write the numbers to the file
    f.write(json.dumps(list(range(0, 1000000))))

nums = None
with open("codes.json", "r") as f: # Read the list in the file to nums
    nums = json.load(f)
    to_remove = int(input("Number to remove: "))
    nums.remove(to_remove) # Removes the number you want to

with open("codes.json", "w") as f: # Dump the list back to the file
    f.write(json.dumps(nums))

CodePudding user response:

Seems like you have different python versions.

There is a difference between built-in python2 open() and python3 open(). Python3 defaults to universal newlines mode, while python2 newlines depends on mode argument open() function.

CSV module docs provides a few examples where open() called with newline argument explicitly set to empty string newline='':

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

Try to do the same. Probably without explicit newline='' your writerows calls add one more newline character.

  • Related