I am trying to make a code block that creates a series of .txt file names. It will open a new file and prompt the user to enter text for the file, continuing until the user doesn't want any more files.
How do I get it to create a series of file names such as file1.txt, file2.txt, file3.txt, etc. ?
filenum = 1
while # getting input from user
outfile = open ("userfile" + str(filenum), 'w')
filenum += 1
# rest of your loop
Assuming you do know in advance how many files are required you can pass a start value to the function range()
fnum = 10
fname = 'file'
ext = '.txt'
for i in range(1, fnum + 1):
with open("{fname}{fnum}{ext}".format(fname=fname, fnum=i, ext=ext), 'w') as f:
# OR for Python 3.6+
# with open(f'{fname}{i}{ext}', 'w') as f:
print(input('User Input: '), file=f)
Related
I need to define a fucntion that will, in short:
Open and grab the content from an existing file
Transform that content
Create a new file
Write that new content in this new file
Print the content of the new file
I'm a complete begginer, but I got this until now. How can I improve this?
def text():
#open the existing file
text_file = open('music.txt', 'r')
#reads the file
reading = text_file.read ()
#this turns everything to lower case, counts the words and displays the list vertically
from collections import Counter
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
#creates a new file and writes the content there
with open('finheiro_saida.txt', 'x') as final_file:
for i in ordem:
finheiro_saida.write(str(i) + '\n')
#not sure how to open this new file and print its content, when I tried it says the new file doesn't exist in the directory - tried everything.
final = open('C:/Users/maria/OneDrive/Documents/SD_DTM/ficheiro_saida.txt', 'r')
read_file = final.read ()
print(read_file)
You can open the new file and print its content the same way you read and wrote to it!
# ...After all your previous code...
with open('finheiro_saida.txt', 'r') as final_file:
final_file_content = final_file.read()
print(final_file_content)
Fixed some syntax error in your code.
you can display the the same way you read.
Also provide all imports to the start of the file.
you can also read all lines from the file as a list using file.readlines()
from collections import Counter
def text():
# open the existing file
text_file = open("music.txt", "r")
# reads the file
reading = text_file.read()
# this turns everything to lower case, counts the words and displays the list vertically
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
# creates a new file and writes the content there
file_name = "finheiro_saida.txt"
with open("finheiro_saida.txt", "x") as final_file:
for i in ordered_list:
final_file.write(str(i) + "\n")
return file_name
def display(final_file_name):
with open(final_file_name) as file:
print(file.read())
final_file_name = text()
display(final_file_name)
As the title side, I am trying to create small programs to do simple calculations on data read in from text files. But I don't know how to turn the elements from the text file into integers. Any help would be greatly appreciated.
enter code heredef main():
f = input('enter the file name')
# this line open the file and reads the content f + '.txt' is required
getinfo = open(f +'.txt','r')
content = getinfo.read()
num = []
print('here are the number in your file', num)
getinfo.close()
main ()
If your .txt file is in this format,
1
2
3
4
Then you can use the split function on content like this:
f = input('enter the file name')
# this line open the file and reads the content f + '.txt' is required
getinfo = open(f +'.txt','r')
content = getinfo.read()
num = content.split("\n") # Splits the content by every new line
print('here are the number in your file', num)
getinfo.close()
If you need everything in num to be of type int then you can do a for loop to do that like this
f = input('enter the file name')
# this line open the file and reads the content f + '.txt' is required
getinfo = open(f +'.txt','r')
content = getinfo.read()
num = content.split("\n") # Splits the content by every new line
for i in range(len(num)):
num[i] = int(num[i])
print('here are the number in your file', num)
getinfo.close()
One thing you need to be careful of, however, is to make sure that your text file doesn't contain any characters instead of numbers, otherwise python will try to convert something like "c" to an integer which will cause an error.
Here below is my code about how to edit text file.
Since python can't just edit a line and save it at the same time,
I save the previous text file's content into a list first then write it out.
For example,if there are two text files called sample1.txt and sample2.txt in the same folder.
Sample1.txt
A for apple.
Second line.
Third line.
Sample2.txt
First line.
An apple a day.
Third line.
Execute python
import glob
import os
#search all text files which are in the same folder with python script
path = os.path.dirname(os.path.abspath(__file__))
txtlist = glob.glob(path + '\*.txt')
for file in txtlist:
fp1 = open(file, 'r+')
strings = [] #create a list to store the content
for line in fp1:
if 'apple' in line:
strings.append('banana\n') #change the content and store into list
else:
strings.append(line) #store the contents did not be changed
fp2 = open (file, 'w+') # rewrite the original text files
for line in strings:
fp2.write(line)
fp1.close()
fp2.close()
Sample1.txt
banana
Second line.
Third line.
Sample2.txt
First line.
banana
Third line.
That's how I edit specific line for text file.
My question is : Is there any method can do the same thing?
Like using the other functions or using the other data type rather than list.
Thank you everyone.
Simplify it to this:
with open(fname) as f:
content = f.readlines()
content = ['banana' if line.find('apple') != -1 else line for line in content]
and then write value of content to file back.
Instead of putting all the lines in a list and writing it, you can read it into memory, replace, and write it using same file.
def replace_word(filename):
with open(filename, 'r') as file:
data = file.read()
data = data.replace('word1', 'word2')
with open(filename, 'w') as file:
file.write(data)
Then you can loop through all of your files and apply this function
The built-in fileinput module makes this quite simple:
import fileinput
import glob
with fileinput.input(files=glob.glob('*.txt'), inplace=True) as files:
for line in files:
if 'apple' in line:
print('banana')
else:
print(line, end='')
fileinput redirects print into the active file.
import glob
import os
def replace_line(file_path, replace_table: dict) -> None:
list_lines = []
need_rewrite = False
with open(file_path, 'r') as f:
for line in f:
flag_rewrite = False
for key, new_val in replace_table.items():
if key in line:
list_lines.append(new_val+'\n')
flag_rewrite = True
need_rewrite = True
break # only replace first find the words.
if not flag_rewrite:
list_lines.append(line)
if not need_rewrite:
return
with open(file_path, 'w') as f:
[f.write(line) for line in list_lines]
if __name__ == '__main__':
work_dir = os.path.dirname(os.path.abspath(__file__))
txt_list = glob.glob(work_dir + '/*.txt')
replace_dict = dict(apple='banana', orange='grape')
for txt_path in txt_list:
replace_line(txt_path, replace_dict)
I am just following a simple Python script to write to a text file. The suggetsed method; adding "\n" to the end didn't work. It is printing within a loopAs I am using Windows, I also tried "\r\n." Still it only prints the last item. I have tried moving everything inside and outside the loop (starting with path and ending with file.close() but no go. What's going on here?
#Assign variables to the shapefiles
park = "Parks_sd.shp"
school = "Schools_sd.shp"
sewer = "Sewer_Main_sd.shp"
#Create a list of shapefile variables
shapeList = [park, school, sewer]
path = r"C:/EsriTraining/PythEveryone/CreatingScripts/SanDiegoUpd.txt"
open(path, 'w')
for shp in shapeList:
shp = shp.replace("sd", "SD")
print shp
file = open(path, 'w')
file.write(shp + "\r\n")
file.close()
Open the file outside the loop
Ex:
with open(path, "w") as infile:
for shp in shapeList:
shp = shp.replace("sd", "SD")
infile.write(shp + "\n")
You can 1) open file outside of the for loop and 2) use writelines
with open(path, 'w+') as f:
f.writelines([shp.replace("sd", "SD")+'\n' for shp in shaplist])
or
with open(path, 'w+') as f:
f.writelines(map(lambda s: s.replace("sd", "SD")+'\n', shaplist))
In this way, you open the file once and once the lines are written, the file is automatically closed (because of the [with]).
i have a python file named file_1.py
it has some code in which, i just have to change a word "file_1" to "file_2"
and also preserve indentation of other functions`
and save it as file_2.py
there are 3 occurances of the word file_1
i have to do this for 100 such times. `file_1.py, file_2.py.....file_100.py`
is there any way to automate this?
Run this script:
import fileinput
with fileinput.FileInput('file_1.py', inplace=True, backup='.bak') as file:
for line in file:
print(line.replace('file_1', 'file_2'), end='')
hope this help :)
create a script:
first: read file
with open("./file1.py") as f:
content = f.read()
second: replace filename
new_content = content.replace("file1","file2")
third: write new file(I would suggest you write a new file)
with open("./file2.py", "w") as f:
f.write(new_content)
if you have multiple files, use something like
filenames = ["file" + str(item) for item in range(1,100)]
for filename in filenames:
with open(filename + ".py") as f:
content = f.read()
new_filename = filename[:-1] + str(int(filename[-1]) + 1)
new_content = content.replace(filename,new_filename)
with open("./another_folder" + new_filename + ".py", "w") as f:
f.write(new_content)