This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 5 years ago.
Kinda new to this, and writing a script that loads in latitudes and longitudes from a CSV file and converts the formatting for another program to read...finally got it all to work.
I was wondering how I might set this up so I could maybe run ./converter.py filename.csv from a command prompt rather then having the filename embedded in the script?
Currently I have this:
csv_file = open('Vicksburg_9mph_dm.csv') #Defines name of file to open
csv_reader = csv.reader(csv_file, delimiter=',') #Opens file as CSV File
Since you said you have a working program (albeit hardcoded for filenames), I'll provide a solution:
import sys
import csv
with open(sys.argv[1], 'r', newline='') as f:
r = csv.reader(f, delimiter=',')
# do your work you already do
A couple notes:
sys module contains access to pass CLI arguments
sys.argv is a list of argument variables as discussed in the docs.
with open() syntax is referred to as a context manager. In your provided code, you technically never called close() so the file remained open. When you exit the with block, the file with automatically close.
newline='' flag is specific to Python 3, if you do not have that version simply omit it
Related
This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 6 months ago.
Running below code in Azure Blobstorage concurrently is throwing
OS Error 22:Invalid argument pointing to f.close()
Is using Close() when using with open() creating OS error 22 issues?
Understand that Close() is not required but want to understand the root cause of OS error 22
*with open(openfilepath,"w+") as f:
f.write(writeFile )
f.close()*
Check the below possibilities and try.
1
If f.close() to be used you may try this by not using with
f = open(file_name, 'w+') # open file in write mode
f.write('write content')
f.close()
BUT
It is good practice to use with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes. once Python exits from the “with” block, the file is automatically closed.
So Please Remove f.close() and try.
with open(file_name, 'w+') as f :
f.write('write content')
Refer this for more info.
2
If above doen’t work check the filepath : It might be due to some invalid characters present in the file path name: It should not contain few special characters.
See if file path is for example : "dbfs:/mnt/data/output/file_name.xlsx"
Check if “/” is there before dbfs ( say /dbfs:/mnt/…).Try Removing if present.
NOTE:
``r+'': Open for reading and writing. The stream is positioned at
the beginning of the file.
``w+'': Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream is positioned at the
beginning of the file.
``a+'' : Open for reading and writing. The file is created if it does
not exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current end of
file, irrespective of any intervening fseek(3) or similar.
So try using other modes like r+ if w+ is not mandatory .See Python documentation
References:
1 , 2 ,3 , 4
Removing the F.close() fixed the issues when using With
This question already has answers here:
Why does my text file keep overwriting the data on it?
(3 answers)
Closed 2 years ago.
So, I did this python program and whenever I run it it says in the file "This is an update" and only one of the quotes I entered. Any help? Program below.
file_name = "my_quote.txt"
new_file = open(file_name, "w")
new_file.close()
def update_file(file_name,quote):
new_file = open(file_name, "w")
new_file.write("This is an update\n")
new_file.write(quote)
new_file.write("\n\n")
new_file.close()
for index in range(1,3):
quote = input("Enter your favorite quote:")
update_file(file_name, quote)
new_file = open(file_name, "r")
print(new_file.read())
new_file.close()
You're opening your file in w mode, which overwrites the file.
Use a for append mode, which, well, appends new content at the end.
You are writing over the current file as you are not opening the file in append mode.
If you change the open command to this instead:
file.open(file_path, 'a')
You will append the text instead of writing over the file.
Whenever you re-open a file, and use write it removes all content previously in the file and overwrites it. And since every time you call update_file you are re-opening it and writeing to it, only the last piece of info written in the last open will be kept (as all previous data was overwritten.
I think you want to use append mode when writing data to the file. See here for a list of all the modes, and their function.
Hope it helps!
This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 3 years ago.
In simplest terms, when i try to run a short amount of code to delete the contents of a file and then rewrite stuff to that file, it pulls that error. I'm trying to get a temperature reading from a com port using the filewrite from CoolTerm, perhaps it's the fact that the file is being used by CoolTerm as well, so I can't edit it, but I'm unsure.
I've tried multiple ways to delete the file information e.g the file.close(), and others, but none seem to work.
while True:
file = open("test.txt","r")
file.truncate()
x = file.read()
x = x.split("\n")
print(x[0])
print(x[1])
time.sleep(3)
I expect the console to output the contents of file but it doesn't. Something that gives me a similar result of what i want would be the Console just outputting the last two entries of the file, rather than having to delete all of it than rewriting it.
Modified to r+ mode is ok, I have tested.
with open('./install_cmd', 'r+') as f:
print(f'truncate ago:{f.read()}')
f.truncate(0)
print(f'truncate after:{f.read()}')
This question already has answers here:
How to create a commit and push into repo with GitHub API v3?
(7 answers)
Closed 4 years ago.
I am trying to read text file from Github repository and then write new stuff into it, I managed to get reading part of the code to work, but obviously the normal file.write() wouldn't work on text file that's in the github repository. So is there way to somehow update text file?
filepath = 'file.txt'
with open(filepath) as fp:
line = fp.readline()
print(line)
#fp.write("This won't work, I know")
you open the file in read mode, which is the default in python,
so:
with open(filepath) as fp:
is equivalent to
with open(filepath, 'r') as fp:
Meaning you open it in read mode,use append mode to write to it
with open(filepath, 'a') as fp:
There is nothing special about github files, the error is in your python code
This question already has answers here:
Create empty file using python [duplicate]
(2 answers)
Closed 8 years ago.
This is the code I have so far, yes I know the 'dirs' code creates a folder, but I am not sure of the code (if there is one) to create a file instead!
import os
if os.path.isfile(outfile):
print("Name already used, please choose another")
else:
os.makedirs(outfile)
Any help would be appreciated :D
Inorder to create a file and work on it, use the open() function.
fp = open(outfile, mode)
modes:
r: read
w: if file exists, replace it with a new one
a: append existing file
In your case the mode is 'w'
For create a file you can just open a file in write mode
open('file.txt', 'w')
https://docs.python.org/3/library/functions.html#open