Str to txt file python

Write String to Text File in Python

In this Python tutorial, you will learn how to write a string value to a text file, using write() method of file class.

Python – Write String to Text File

To write string to a file in Python, we can call write() function on the text file object and pass the string as argument to this write() function.

In this tutorial, we will learn how to write Python String to a file, with the help of some Python example programs.

Following is the step by step process to write a string to a text file.

  1. Open the text file in write mode using open() function. The function returns a file object.
  2. Call write() function on the file object, and pass the string to write() function as argument.
  3. Once all the writing is done, close the file using close() function.
Читайте также:  Открыть файл тип html

Examples

1. Write string to new text file

The following is an example Python program in its simplest form to write string to a text file.

Python Program

#open text file text_file = open("D:/data.txt", "w") #write string to file text_file.write('Python Tutorial by TutorialKart.') #close file text_file.close()

Reference tutorials for the above program

When we run this program, a new file is created named data.txt in D: drive and the string is written to the file. But to programmatically confirm, you can use the value returned by write() function. write() function returns the number of bytes written to the file.

Python Program

#open text file text_file = open("D:/data.txt", "w") #write string to file n = text_file.write('Python Tutorial by TutorialKart.') #close file text_file.close() print(n)

2. Write string value to an existing file

If you try to write a string to an existing file, be careful. When you create a file in write mode and call write() function, existing data is lost and new data is written to the file.

For instance, in the previous example, we created a file and written some data to it.

Now we shall run the following example.

Python Program

#open text file text_file = open("D:/data.txt", "w") #write string to file n = text_file.write('Hello World!') #close file text_file.close()

The existing file is overwritten by the new content.

Note: If you would like to append data to a file, open file in append mode and then call write() function on the file object.

Conclusion

In this Python Tutorial, we learned how to write a string to a text file.

Источник

How to Write String to Text File in Python?

Now you can save or write string to text a file in persistent data storage using Python.

To write string to a Text File, follow these sequence of steps:

  1. Open file in write mode using open() function.
  2. Write string to the file using write() method.
  3. Close the file using close() method.

Examples

1. Write string to text file

In the following example, we will take a string constant and write the string to a text file by following the above said sequence of steps.

Python Program

text_file = open("sample.txt", "w") n = text_file.write('Welcome to pythonexamples.org') text_file.close()

The write() method returns the number of characters written to the text file.

Note that this kind of writing to text file, overwrites the data, if the file is already present. If the file is not present, it creates a new file and then writes the string to the file.

2. Write string to text file in text mode

A file can be opened in two modes: the first one is text mode and the second one is binary mode. By default a file is opened in text mode. However, you can explicitly specify the mode.

In the following example, we will open the file in text mode by appending “t” to the mode and write the string to a text file by following the sequence of steps mentioned at the start of this tutorial.

Python Program

text_file = open("sample.txt", "wt") n = text_file.write('Welcome to pythonexamples.org') text_file.close()

Writing other than String to Text File

If you would like to write any Python object other than string or a bytes object to a file, using write() method, you should first convert that Python object to a string or bytes object.

Summary

In this tutorial of Python Examples, we learned how to write a string to a text file, with the help of example programs.

Источник

How to Write a String to a Text File using Python

Data to Fish

Steps to Write a String to a Text File using Python

Step 1: Specify the path for the text file

To begin, specify the path where the text file will be created.

For example, let’s suppose that a text file will be created under the following path:

Step 2: Write a string to a text file using Python

Next, write your string to the text file using this template:

text_file = open(r'path where the text file will be created\file name.txt', 'w') my_string = 'type your string here' text_file.write(my_string) text_file.close()
  • The path where the text file will be created is: C:\Users\Ron\Desktop\Test
  • The file name (with the txt file extension) is: Example.txt
  • my_string contains the following text: ‘This is a Test

So the full Python code would look as follows (don’t forget to place ‘r‘ before your path name to avoid any errors in the path):

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') my_string = 'This is a Test' text_file.write(my_string) text_file.close()

Once you run the code (adjusted to your path), you’ll then see the new text file in your specified location.

If you open the text file, you’ll see the actual string:

Overwrite the String

What if you want to overwrite the original string with a new value?

For instance, what if you want to change the string to the following value:

This is a NEW Test

In that case, simply edit the text as follows:

my_string = 'This is a NEW Test'

So the new Python code would look like this:

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') my_string = 'This is a NEW Test' text_file.write(my_string) text_file.close()

Run the code, and you’ll see the new string:

List of Strings

Say that you want to display a list of strings in your text file.

Here is an example of a list with strings:

my_list = ['This is a Test', 'This is ALSO a Test', 'This is a FINAL Test']

In that case, you may use a for loop to display your list of strings in the text file:

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') my_list = ['This is a Test', 'This is ALSO a Test', 'This is a FINAL Test'] for i in my_list: text_file.write(i + '\n') text_file.close()

You’ll now see that each of the strings is presented in a new line:

Dealing with Integers

If you try to print integers into the text file, you’ll get the following error:

write() argument must be str, not int

You may then choose to convert the integers to strings.

For example, let’s suppose that you have two integers (3 and 5), and you want to present the sum of those integers in the text file.

In that case, you may apply the following syntax to achieve the above goal (notice that str() was used to convert the integers to strings):

text_file = open(r'C:\Users\Ron\Desktop\Test\Example.txt', 'w') sum_values = 3 + 5 text_file.write(str(sum_values)) text_file.close()

You’ll then get the sum of 8 in the text file:

Источник

How to Use Python to Write a Text File (.txt)

How to Use Python to Write a Text File (txt) Cover Image

In this tutorial, you’ll learn how to use Python to write (or save) to a text file. Python provides incredible opportunity to read and work with text files – being able to save the output to a text file is an important skill. Python can handle both regular text files and binary files – in this tutorial, you’ll learn how to work with text files.

By the end of this tutorial, you’ll have learned:

  • How to use Python to write to a .txt file
  • How to use a context manager to safely write to a text file
  • How to append text to a file in Python
  • How to write UTF-8 text to a File in Python

How to Use Python to Write to a Text File

Python provides a number of ways to write text to a file, depending on how many lines you’re writing:

  • .write() will write a single line to a file
  • .writelines() will write multiple lines to a file

These methods allow you to write either a single line at a time or write multiple lines to an opened file. While Python allows you to open a file using the open() , it’s best to use a context manager to more efficiently and safely handle closing the file.

Let’s see what this looks like:

# Writing a Single Line to a Text File text = 'Welcome to datagy.io!' with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: f.write(text)

Let’s break down what the code above is doing:

  • We load a string that holds our text in a variable text
  • We then use a context manager to open a file in ‘w’ mode, which allows us to overwrite an existing text
  • The file doesn’t need to exist – if it doesn’t, it’ll automatically be created
  • When then use the .write() method to write our string to the file

Writing Multiple Lines to a Text File Using Python

In many cases, you may not want to write a single line of text to a file. Let’s take a look at how we can write multiple lines of text to a file using the .write() method:

# Writing Multiple Lines to a Text File text = ['Welcome to datagy.io!', "Let's learn some Python!"] with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: for line in text: f.write(line) f.write('\n')

Let’s take a look at what we’re doing in the code above:

  • We load a list of strings that contains the lines of text we want to save
  • Similar to the previous example, we open the file using a context manager
  • We then loop over each item in the list to write each string to the file
  • For each item, we also write a newline character so that each line is split across a new line

The approach above feels a bit clunky. We can simplify this process by using the .writelines() method, which allows us to write multiple lines at once. Let’s see how we can modify our code above to use the .writelines() method:

# Writing Multiple Lines to a Text File (with .writelines) text = ['Welcome to datagy.io', "Let's learn some Python!"] with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: f.writelines('\n'.join(text))

In the code above, we avoid using a for loop to write multiple lines of text to a file. Because our text isn’t separated by newline characters, we use the .join() string method to place each item onto a new line.

How to Append to a Text File in Python

In the previous sections, you learned how to write a new file with text in Python. In this section, you’ll learn how to append to a given text file using Python. We previously used the write mode, ‘w’ when opening the file – in order to append, we use the append mode, ‘a’ .

Let’s see how we can append to a text file in Python:

# Appending to a Text File in Python text = 'Welcome to datagy.io!\n' with open('/Users/nikpi/Desktop/textfile.txt', 'a') as f: f.write(text)

Running this will append to the end of the text file. Note that we applied the newline character into the string. This could also be done in the context manager, depending on how you prefer your code to run.

Similarly, we can append multiple lines to a file by using the .writelines() method, as shown below:

# Appending Multiple Lines to a Text File text = ['Welcome to datagy.io!\n', 'Python is fun!\n'] with open('/Users/nikpi/Desktop/textfile.txt', 'a') as f: f.writelines(text)

How to Write UTF-8 Encoded Text to a File in Python

Python will open a file using the system’s default encoding. While UTF-8 is the de-facto standard, your system may not open the file using that encoding format. Because of this, you may need to specify the encoding format when opening the file.

Let’s see how we can do this:

# Specifying Encoding to UTF-8 text = 'é' with open('/Users/nikpi/Desktop/textfile.txt', 'w', encoding="utf-8") as f: f.write(text)

Running this code on, for example, macOS, doesn’t require specifying the encoding. However, if you want your code to run platform independently, it is a good idea to specify the encoding.

Conclusion

In this tutorial, you learned how to use Python to write a text file. You first learned about the different ways of overwriting a file using the .write() and .writelines() methods. You learned about the nuances of inserting newline characters. Then, you learned how to append to an existing file, both single lines as well as multiple lines. Finally, you learned how to specify the encoding when writing a file.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

Оцените статью